开发者

perform multiple for loops simultaneously

Is it possible to perform multiple loops simultaneously in python.

Like(syntax error, of course):

for a,b in list_of_a,list_of_b:
      //do some thing

By simultaneously, I am not meaning the thread or process sense.

开发者_如何学编程

I mean, they share the same index or cursor during the iteration.

What I can think of achieving that is:

  1. Use a int variable to act as a shared cursor
  2. put them in a list of tuples and iterate the tuple-list. But creating the list is laborious

I am just wondering if there some built-in functions or simpler syntax to achieve that.


for a,b in zip(list_of_a, list_of_b):
  # Do some thing

If you're using Python 2.x, are worried about performance, and/or using iterators instead of lists, consider itertools.izip instead of zip.

In Python 3.x, zip replaces itertools.izip; use list(zip(..)) to get the old (2.x) behavior of zip returning a list.


import itertools
for a, b in itertools.izip(list_a, list_b):
    # ...
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜