Home > Enterprise >  How to run a for loop on a list
How to run a for loop on a list

Time:07-17

enter image description here

I was trying to test if the number 1 existed in a given list. However, my lists are named dia_{x}. So in order to run the code, I need to say "if 1 in dia_i" where i is every integer between 1 and 18 inclusive. However, there is no way that I know of to append "i" to "dia_" without it being a string variable. Please help!

dia_1 = [0]
dia_2 = [0, 0]
dia_3 = [0, 0, 0]
dia_4 = [0, 0, 0, 0]
dia_5 = [0, 0, 1, 0, 0]
dia_6 = [0, 0, 0, 0,]
dia_7 = [0, 0, 0]
dia_8 = [0, 0]
dia_9 = [0]

dia_10 = [0]
dia_11 = [0, 0]
dia_12 = [0, 0, 0]
dia_13 = [0, 0, 0, 0]
dia_14 = [0, 0, 1, 0, 0]
dia_15 = [0, 0, 0, 0,]
dia_16 = [0, 0, 0]
dia_17 = [0, 0]
dia_18 = [0]

for i in range(1):
    if 1 in :
        print('yes')
    else:
        print('no')

CodePudding user response:

You need to consider about storing it in a same list which you can loop through it.

dia = [
    dia_1, dia_2, dia_3, dia_4, dia_5,
    dia_6, dia_7, dia_8, dia_9, dia_10,
    dia_11, dia_12, dia_13, dia_14, dia_15,
    dia_16, dia_17, dia_18,
]

for d in dia:
    if 1 in d: print("YES")
    else: print("NO")

However, you can try to use eval:

for i in range(1,19):
    if 1 in eval('dia_' str(i)): print("YES")
    else: print("NO")

CodePudding user response:

You have to do it by defining a function

def find_number(numbers, lists):
    for list in lists:
        for number in numbers:
             if number in list:
                  return True
    return False

Since you only check for 1

def find_number(lists):
    for list in lists:
             if 1 in list:
                  return True, 
    return False

The problem is you will not able to return the list name in Python. Not optimal but you can achieve it by following

dia_1 = [0]
dia_2 = [0, 0]
dia_3 = [0, 0, 0]
dia_4 = [0, 0, 0, 0]
dia_5 = [0, 0, 1, 0, 0]

def find_number(*lists):
    which_list = 0
    for list in lists:
        which_list  = 1
        if 1 in list:
            list_name = "dia_"   str(which_list)
            print(list_name)
            return True, list_name
    return False

isThere, name = find_number(dia_1, dia_2, dia_3, dia_4, dia_5)

The latest code should give you what you need.

CodePudding user response:

Why not use a dictionary?

my_dict = {
    "dia_1": [0],
    "dia_2": [0, 0],
    "dia_3": [0, 0, 0],
    "dia_4": [0, 0, 0, 0],
    "dia_5": [0, 0, 1, 0, 0],
    "dia_6": [0, 0, 0, 0, ],
    "dia_7": [0, 0, 0],
    "dia_8": [0, 0],
    "dia_9": [0],
    "dia_10": [0],
    "dia_11": [0, 0],
    "dia_12": [0, 0, 0],
    "dia_13": [0, 0, 0, 0],
    "dia_14": [0, 0, 1, 0, 0],
    "dia_15": [0, 0, 0, 0, ],
    "dia_16": [0, 0, 0],
    "dia_17": [0, 0],
    "dia_18": [0]
}

for k, v in my_dict.items():
    if 1 in v:
        print('yes')
    else:
        print('no')
# access any key
    print(my_dict.get('dia_5'))
  • Related