列表理解列表 [英] List comprehension list of lists

查看:42
本文介绍了列表理解列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

所以,我有

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]

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

Or use this if you know map:

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

这篇关于列表理解列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆