简体   繁体   English

迭代Python中的第一次迭代

[英]Iterating over first iteration in Python

Is there a one-liner or Pythonic (I'm aware that the former doesn't necessarily imply the latter) way to write the following nested loop? 是否存在单行或Pythonic(我知道前者不一定暗示后者)的方式来编写以下嵌套循环?

for i in some_list:
    for j in i:
        # do something

I've tried 我试过了

import itertools
for i,j in itertools.product(some_list,i):
    # do something

but I get a 'reference before assignment error', which makes sense, I think. 但我认为“分配错误之前有参考”,我认为这很有意义。 I've been unable to find an answer to this question so far... Any suggestions? 到目前为止,我一直找不到这个问题的答案...有什么建议吗? Thanks! 谢谢!

If you want to iterate through each sub-list in some_list in turn you can use itertools.chain : 如果要依次遍历some_list中的每个子列表, some_list可以使用itertools.chain

for j in itertools.chain(*some_list):

A short demo: 简短的演示:

>>> import itertools
>>> some_list = [[1, 2], [3, 4]]
>>> for j in itertools.chain(*some_list):
    print j


1
2
3
4

Alternatively there is chain.from_iterable : 另外,还有chain.from_iterable

>>> for j in itertools.chain.from_iterable(some_list):
    print j


1
2
3
4

(Aside from the slight syntax change, see this question for an explanation of the difference.) (除了语法上的细微变化外,请参阅此问题以获取区别的说明。)

Use chain: 使用链:

import itertools


some_list = [[1,2,3,4],[3,4,5,6]]

for i in itertools.chain(*some_list):
    print i
1
2
3
4
3
4
5
6

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

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