简体   繁体   English

列表理解嵌套循环,多种操作

[英]List Comprehension Nested Loop, Multiple Operations

Given a list like so: 给出如下列表:

[[1,2,3],[4,5,6],[7,8,9]]

I'm trying to get my output to look like this, with using only a list comprehension: 我试图仅使用列表理解来使输出看起来像这样:

1 2 3
4 5 6
7 8 9

Right now I have this: 现在我有这个:

[print(x,end="") for row in myList for x in row]

This only outputs: 这仅输出:

1 2 3 4 5 6 7 8 9

Is there a way to have it break to a new line after it processes each inner list? 处理每个内部列表后,是否有办法使其换行?

You could do like the below. 您可以像下面这样。

>>> l = [[1,2,3],[4,5,6],[7,8,9]]
>>> for i in l:
        print(' '.join(map(str, i)))


1 2 3
4 5 6
7 8 9

You can do as follows: 您可以执行以下操作:

print("\n".join(" ".join(map(str, x)) for x in mylist))

Gives: 给出:

1 2 3
4 5 6
7 8 9
>>> l = [[1,2,3],[4,5,6],[7,8,9]]
>>> for line in l:
        print(*line)
1 2 3
4 5 6
7 8 9

A good explanation of the star in this answer . 这个答案很好地解释了星星。 tl;dr version: if line is [1, 2, 3] , print(*line) is equivalent to print(1, 2, 3) , which is distinct from print(line) which is print([1, 2, 3]) . tl; dr版本:如果line[1, 2, 3] ,则print(*line)等效于print(1, 2, 3) ,这与print(line)print([1, 2, 3])

I agree with Ashwini Chaudhary that using list comprehension to print is probably never the "right thing to do". 我同意Ashwini Chaudhary的观点,即使用列表理解来打印可能永远不是“正确的事情”。

Marcin's answer is probably the best one-liner and Andrew's wins for readability. Marcin的答案可能是最好的一线客,而Andrew的可读性则胜出。

For the sake of answering the question that was asked... 为了回答所提出的问题...

>>> from __future__ import print_function # python2.x only
>>> list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> [print(*x, sep=' ') for x in list]
1 2 3
4 5 6
7 8 9
[None, None, None]

Try this: print("\\n".join([' '.join([str(val) for val in list]) for list in my_list])) 试试这个: print("\\n".join([' '.join([str(val) for val in list]) for list in my_list]))

In [1]:  my_list = [[1,2,3],[4,5,6],[7,8,9]]

In [2]: print("\n".join([' '.join([str(val) for val in list]) for list in my_list]))

1 2 3
4 5 6
7 8 9

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

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