Python: Nested Loop

2019-07-20 02:19发布

Consider this:

>>> a = [("one","two"), ("bad","good")]

>>> for i in a:
...     for x in i:
...         print x
... 
one
two
bad
good

How can I write this code, but using a syntax like:

for i in a:
    print [x for x in i]

Obviously, This does not work, it prints:

['one', 'two']
['bad', 'good']

I want the same output. Can it be done?

8条回答
聊天终结者
2楼-- · 2019-07-20 02:40

Given your example you could do something like this:

a = [("one","two"), ("bad","good")]

for x in sum(map(list, a), []):
    print x

This can, however, become quite slow once the list gets big.

The better way to do it would be like Tim Pietzcker suggested:

from itertools import chain

for x in chain(*a):
    print x

Using the star notation, *a, allows you to have n tuples in your list.

查看更多
家丑人穷心不美
3楼-- · 2019-07-20 02:47
import itertools
for item in itertools.chain(("one","two"), ("bad","good")):
    print item

will produce the desired output with just one for loop.

查看更多
相关推荐>>
4楼-- · 2019-07-20 02:50

The print function really is superior, but here is a much more pythonic suggestion inspired by Benjamin Pollack's answer:

from __future__ import print_function
for x in a:
    print(*x, sep="\n")

Simply use * to unpack the list x as arguments to the function, and use newline separators.

查看更多
爷、活的狠高调
5楼-- · 2019-07-20 02:51

You'll need to define your own print method (or import __future__.print_function)

def pp(x): print x

for i in a:
  _ = [pp(x) for x in i]

Note the _ is used to indicate that the returned list is to be ignored.

查看更多
别忘想泡老子
6楼-- · 2019-07-20 02:53

This code is straightforward and simpler than other solutions here:

for i in a:
    print '\n'.join([x for x in i])
查看更多
smile是对你的礼貌
7楼-- · 2019-07-20 02:55

Not the best, but:

for i in a:
    some_function([x for x in i])

def some_function(args):
    for o in args:
        print o
查看更多
登录 后发表回答