简体   繁体   中英

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?

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 :

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 :

>>> 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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