Python: Nested Loop

谁说胖子不能爱 提交于 2020-01-04 05:33:17

问题


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?


回答1:


>>> a = [("one","two"), ("bad","good")]
>>> print "\n".join(j for i in a for j in i)
one
two
bad
good



>>> for i in a:
...  print "\n".join(i)
... 
one
two
bad
good



回答2:


List comprehensions and generators are only designed to be used as expressions, while printing is a statement. While you can effect what you're trying to do by doing

from __future__ import print_function
for x in a:
    [print(each) for each in x]

doing so is amazingly unpythonic, and results in the generation of a list that you don't actually need. The best thing you could do would simply be to write the nested for loops in your original example.




回答3:


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.




回答4:


import itertools
for item in itertools.chain(("one","two"), ("bad","good")):
    print item

will produce the desired output with just one for loop.




回答5:


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.




回答6:


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.




回答7:


This code is straightforward and simpler than other solutions here:

for i in a:
    print '\n'.join([x for x in i])



回答8:


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


来源:https://stackoverflow.com/questions/1821471/python-nested-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!