简体   繁体   English

嵌套在带有列表的python中的for循环

[英]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: 使用zip函数,如下所示:

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. 假设您有10个元素的列表。 Iterating over it with a for loop will take 10 iterations. 使用for循环对其进行迭代将需要10次迭代。 If you have another list of 5 elements, iterating over it with a for loop will take 5 iterations. 如果您还有5个元素的列表,则使用for循环对其进行迭代将需要5次迭代。 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. 现在,如果嵌套这两个循环,则必须执行50次迭代以覆盖每个列表中元素的每种可能组合。

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. 我建议使用dict而不是2个列表,因为您显然希望将它们关联。

Dicts are explained here 字典在这里解释

Once you have your dicts set up you will be able to say 字典设置好后,您就可以说

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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