简体   繁体   English

Python结构化循环多个项目

[英]Python structured looping over multiple items

I would like to loop over three lists 我想循环三个列表

['A','B'],[1,2],[3,4]

If I wanted to loop over all possibilities, I could have done this: 如果我想绕过所有可能性,我本可以做到这一点:

for i,j,k in zip(['A','B'],[1,2],[3,4])

However, I want to loop in a certain manner. 但是,我想以某种方式循环。 I want to iterate over 'A',1 and 'B',2 for all possible values of the last list. 我想迭代'A',1 and 'B',2为最后一个列表的所有可能值。 Thus I want to exclude the combinations 因此,我想排除这些组合

 'A',2 and 'B',1.

Basically I want to generate the following items. 基本上我想生成以下项目。 'A',1,3 'A',1,4 'B',2,3 B',2,4

I am clueless on how to do it. 我对如何做到这一点毫无头绪。

Because you want to keep 'a' tied together with 1, and 'b' with 2, you should zip the first two lists together. 因为你想保持'a'与1绑在一起,'b'与2绑在一起,你应该将前两个列表压缩在一起。 And because you want to iterate over 3 and 4 regardless of which choice you make in the first part, that should be a separate iteration, not part of the zip. 而且因为无论你在第一部分中做出哪个选择,你想迭代3和4,这应该是一个单独的迭代,而不是zip的一部分。

[(i,j,k) for k in [3, 4] for i,j in zip(['a', 'b'], [1, 2])]

# [('a', 1, 3), ('b', 2, 3), ('a', 1, 4), ('b', 2, 4)]

You could use itertools.product 你可以使用itertools.product

from itertools import product
for a,b in product(zip(l1,l2), l3):
        print (a[0], a[1], b)

A 1 3
A 1 4
B 2 3
B 2 4

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

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