Python:列表理解列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21507319/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:01:26  来源:igfitidea点击:

Python: List comprehension list of lists

pythonlistpython-2.7

提问by Jean-Luc

I have a list of lists, and would like to use list comprehension to apply a function to each element in the list of lists, but when I do this, I end up with one long list rather than my list of lists.

我有一个列表列表,并且想使用列表理解将函数应用于列表列表中的每个元素,但是当我这样做时,我最终得到一个长列表而不是我的列表列表。

So, I have

所以我有

x = [[1,2,3],[4,5,6],[7,8,9]]
[number+1 for group in x for number in group]
[2, 3, 4, 5, 6, 7, 8, 9, 10]

But I want to get

但我想得到

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

How do I go about doing this?

我该怎么做?

采纳答案by Booster

Use this:

用这个:

[[number+1 for number in group] for group in x]

Or use this if you know map:

或者,如果您知道地图,请使用它:

[map(lambda x:x+1 ,group) for group in x]

回答by Shirutzen

lista = [[i+3*(j-1) for i in range(1,4)] for j in range(1,4)]

print(lista)
# outputs [[1, 2, 3], [4, 5, 6], [7, 8, 9]]