有没有一种方法可以并行 - 每个循环? [英] Is there a way to have parallel for-each loops?
问题描述
(len(list1))中的listIndex :
doSomething(list1 [listIndex])
doSomething(list2 [listIndex])
但是有没有办法更直观地做到这一点,用foreach循环?就像在list1中的list1Value,在list2中的list2Value
...?
我目前遇到这种情况在Python中,但这是一个长期的问题,我很想知道你是否可以用任何语言来做到这一点。 (我只是假设Python是最有可能的方法来处理这个问题。)
类似这样? / b>
for(a,b)in zip(list1,list2):
doSomething(a)
doSomething (b)
虽然如果 doSomething()
不是在执行I / O或更新全局状态,它只是在一个元素上工作,顺序无关紧要,所以你可以使用 chain()$ c $对于链中的x(list1,list2),
:
doSomething(x)
Apropos, izip()
,而不是使用上面给出的 zip()
。也可以看看 izip_longest()
, izip(count(),lst)
等等。 : - )
哦,和压缩也适用于更多的列:
for idx,a,b,c in izip(count(),A,B,C):
...
Let's say I have 2 lists in Python and I want to loop through each one in parallel - e.g. do something with element 1 for both lists, do something with element 2 for both lists... I know that I can do this by using an index:
for listIndex in range(len(list1)):
doSomething(list1[listIndex])
doSomething(list2[listIndex])
But is there a way to do this more intuitively, with a foreach loop? Something like for list1Value in list1, list2Value in list2
...?
I've currently run into this situation in Python, but this is a longstanding question and I'd be interested to know if you can do this in any language. (I just assumed that Python is the most likely to have a method of dealing with this.)
Something like this?
for (a,b) in zip(list1, list2):
doSomething(a)
doSomething(b)
Though if doSomething()
isn't doing I/O or updating global state, and it just works on one of the elements at a time, the order doesn't matter so you could just use chain()
(from itertools):
for x in chain(list1, list2):
doSomething(x)
Apropos, from itertools import *
is something I do very often. Consider izip()
instead of using the zip()
I gave above. Also look into izip_longest()
, izip(count(), lst)
, etc. Welcome to functional programming. :-)
Oh, and zipping also works with more "columns":
for idx, a, b, c in izip(count(), A, B, C):
...
这篇关于有没有一种方法可以并行 - 每个循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!