Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/283.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 列表理解列表的列表_Python_List_Python 2.7 - Fatal编程技术网

Python 列表理解列表的列表

Python 列表理解列表的列表,python,list,python-2.7,Python,List,Python 2.7,我有一个列表,希望使用列表理解将函数应用于列表中的每个元素,但当我这样做时,我得到的是一个长列表,而不是列表 所以,我有 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] 但是我想 [[2, 3, 4], [5, 6, 7], [8, 9, 10]] 我该怎么做呢?使用以下方法: [[number+1 for number in gr

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

所以,我有

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]
但是我想

[[2, 3, 4], [5, 6, 7], [8, 9, 10]]
我该怎么做呢?

使用以下方法:

[[number+1 for number in group] for group in x]
或者,如果您知道地图,请使用此选项:

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

从数据结构开始:

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

每个组都是<强>三重<<强> [a,b,c],所以我考虑可读性的一个解决方案,比如:

«从列表中选取每组[a、b、c],并向我提供[a+1、b+1、c+1]的列表。»


x\u increased=[[a+1,b+1,c+1]对于x中的[a,b,c]

我意识到OP使用的是python2,但是对于使用python3的未来用户,map返回一个map对象,因此您必须对x中的group执行
[list(map(lambda x:x+1,group)]
以获得相同的结果。哦,thx。我现在已经习惯了Python2.7.2,将来我会尝试使用Python3。欢迎来到SO!在设计答案时,重要的是要包含一些解释,说明代码是如何创建一个更健壮的答案的。如果您需要其他帮助,请查看。
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]]