开发者

Combine enumerate + itertools.izip in Python

开发者 https://www.devze.com 2023-03-29 04:11 出处:网络
I would like to iterate + enumerate over two lists in Python. The following开发者_StackOverflow中文版 code looks ugly. Is there any better solution?

I would like to iterate + enumerate over two lists in Python. The following开发者_StackOverflow中文版 code looks ugly. Is there any better solution?

for id, elements in enumerate(itertools.izip(as, bs)):
  a = elements[0]
  b = elements[1]
  # do something with id, a and b

Thank you.


You can assign a and b during the for loop:

for id, (a, b) in enumerate(itertools.izip(as, bs)):
  # do something with id, a and b


You could use itertools.count instead of enumerate:

for id_, a, b in itertools.izip(itertools.count(), as_, bs):
  # do something with id_, a and b

Note that I've changed the variable names slightly to avoid a reserved word and the name of a builtin.

0

精彩评论

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