繁体   English   中英

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

[英]nested for loops in python with lists

乡亲-我有两个清单

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

我想将变量发送到如下函数:

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

我的脚本:

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

我收到以下输出:

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

我希望它看起来像这样:

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

使用zip函数,如下所示:

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

输出:

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

你为什么这么认为呢?

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

嵌套循环将针对其父循环中的每个迭代执行。 考虑一下真值表:

p q
0 0
0 1
1 0
1 1

或组合:

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

假设您有10个元素的列表。 使用for循环对其进行迭代将需要10次迭代。 如果您还有5个元素的列表,则使用for循环对其进行迭代将需要5次迭代。 现在,如果嵌套这两个循环,则必须执行50次迭代以覆盖每个列表中元素的每种可能组合。

您有很多解决方案。

# 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])

我建议使用dict而不是2个列表,因为您显然希望将它们关联。

字典在这里解释

字典设置好后,您就可以说

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

暂无
暂无

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

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