简体   繁体   English

列表理解列表列表

[英]List comprehension list of lists

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?我该怎么做?

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]

Starting from the structure of your data:从数据结构开始:

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

Every group is a triplet [a,b,c], so I consider for readability a solution like:每个组都是一个三元组[a,b,c],所以为了可读性,我考虑了一个解决方案,如:

«take every group [a,b,c] from the list and provide me the list of [a+1,b+1,c+1] » «从列表中取出每组 [a,b,c] 并提供给我[a+1,b+1,c+1] 的列表»

x_increased = [ [a+1,b+1,c+1] for [a,b,c] in x ]

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]]

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

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