在Python中使用多个条件的for循环

4

我有三个等大小的列表(List1、2和3),我想遍历每个列表并对其中的每个项目执行操作,例如:

for x in List1, y in List2, z in List3:
    if(x == "X" or x =="x"):
         //Do operations on y
    elif(y=="Y" or y=="y"):
         //Do operations on x,z

我希望能够通过Python遍历列表 "List1或2或size的长度",然后对x、y和z执行操作。您该如何做到这一点呢?

编辑:Python版本为2.6.6

2个回答

8
import itertools
for x, y, z in itertools.izip(List1, List2, List3):
    # ...

在Python 3中,您可以使用zip函数。

@wim:如果您想多次使用压缩列表,那么这将是很好的。如果您只想迭代一次,最好使用迭代器/视图来处理它。 - Cat Plus Plus
但是我正在使用Python 2.6.6,而itertools未定义。 - SyncMaster
2
itertools 已经包含在 Python 2.6 中,您只需要导入它即可。 - Alasdair

0
>>> map(lambda x, y, z: (x, y, z), range(0, 3), range(3, 6), range(6, 9))
[(0, 3, 6), (1, 4, 7), (2, 5, 8)]

现在我明白为什么GvR不想让map、reduce等功能出现在这门语言中了。 :/ - Karl Knechtel
@karl-knechter,顺便问一下,替换reduce的首选方法是什么? - newtover
我认为你应该明确地编写一个for循环。注意,我并没有说我同意。 ;) - Karl Knechtel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接