伙计 - 我有两个清单
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)
答案 0 :(得分:6)
使用zip
功能,如下所示:
list1=['a','b']
list2=['y','z']
for i, j in zip(list1, list2):
print(i, j)
输出:
('a', 'y')
('b', 'z')
答案 1 :(得分:2)
为什么你认为这是?
>>> 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])
答案 2 :(得分:0)