简体   繁体   中英

nested for loops in python with lists

Folks - I have two lists

list1=['a','b']
list2=['y','z']

I would like to send the variables to a function like below:

 associate_address(list1[0],list2[0])
 associate_address(list1[1],list2[1])

my script:

for l in list1:
 for i in list2:
  conn.associate_address(i,l)

I receive the below output:

conn.associate_address(a,y)
conn.associate_address(a,z)

I would like it to look like this:

conn.associate_address(a,y)
conn.associate_address(b,z)

Use the zip function, like this:

list1=['a','b']
list2=['y','z']
for i, j in zip(list1, list2):
    print(i, j)

Output:

('a', 'y')
('b', 'z')

Why do you suppose this is?

>>> for x in [1,2]:
...     for y in ['a','b']:
...             print x,y
... 
1 a
1 b
2 a
2 b

Nested loops will be performed for each iteration in their parent loop. Think about truth tables:

p q
0 0
0 1
1 0
1 1

Or combinations:

Choose an element from a set of two elements.
2 C 1 = 2

Choose one element from each set, where each set contains two elements.
(2 C 1) * (2 C 1) = 4

Let's say you have a list of 10 elements. Iterating over it with a for loop will take 10 iterations. If you have another list of 5 elements, iterating over it with a for loop will take 5 iterations. Now, if you nest these two loops, you will have to perform 50 iterations to cover every possible combination of the elements of each list.

You have many options to solve this.

# use tuples to describe your pairs
lst = [('a','y'), ('b','z')]
for pair in lst:
    conn.associate_address(pair[0], pair[1])

# use a dictionary to create a key-value relationship
dct = {'a':'y', 'b':'z'}
for key in dct:
    conn.associate_address(key, dct[key])

# use zip to combine pairwise elements in your lists
lst1, lst2 = ['a', 'b'], ['y', 'z']
for p, q in zip(lst1, lst2):
    conn.associate_address(p, q)

# use an index instead, and sub-index your lists
lst1, lst2 = ['a', 'b'], ['y', 'z']
for i in range(len(lst1)):
    conn.associate_address(lst1[i], lst2[i])

I would recommend using a dict instead of 2 lists since you clearly want them associated.

Dicts are explained here

Once you have your dicts set up you will be able to say

>>>mylist['a']
y
>>>mylist['b']
z

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM