[英]How do I create a new list with specific items from an old list in Python 2?
I have a list of lists (I think) that looks like this: 我有一个看起来像这样的列表列表:
[['Cats', 'Dogs', '', 'Gerbils'],
['Tigers', 'Snakes', '', 'Hamsters'],
['Iguanas', 'Snails', '', 'Worms']]
I need to build a new list of lists by ignoring the blank fields. 我需要通过忽略空白字段来构建新的列表列表。 So my new lists would look like this: 因此,我的新列表如下所示:
[['Cats', 'Dogs', 'Gerbils'],
['Tigers', 'Snakes', 'Hamsters'],
['Iguanas', 'Snails','Worms']]
I've not got a deep understanding of lists in Python so I'm at a complete loss as to how to do this. 我对Python中的列表没有很深入的了解,因此我对如何执行此操作一无所知。 Can anyone point me to doc that will show me the way? 谁能指出我要给我指路的文档?
Thanks! 谢谢!
Edit: list-of-lists syntax corrected by Dan 编辑:Dan纠正的列表语法
l = [['Cats', 'Dogs', '', 'Gerbils'],
['Tigers', 'Snakes', '', 'Hamsters'],
['Iguanas', 'Snails', '', 'Worms']]
[[i for i in sub if i] for sub in l]
Output 输出量
[['Cats', 'Dogs', 'Gerbils'],
['Tigers', 'Snakes', 'Hamsters'],
['Iguanas', 'Snails', 'Worms']]
newlist = [ filter(None, x) for x in oldlist ]
Edited in response to comments: 编辑以回应评论:
It is arguable that using filter(bool, x)
is more readable than filter(None, x)
. 可以说使用filter(bool, x)
比filter(None, x)
更具可读性。 In effect they are the same, both meaning "filter out the items that are false/None/empty/zero". 实际上,它们是相同的,都意味着“过滤掉错误/无/空/零的项目”。
In python 3, filter
returns an iterable object rather than a list, so the equivalent would be 在python 3中, filter
返回一个可迭代的对象而不是列表,所以等效的将是
newlist = [ list(filter(None, x)) for x in oldlist ]
or 要么
newlist = [ list(filter(bool, x)) for x in oldlist ]
each of which is equivalent to 每个等价于
[ [ item for item in x if item ] for x in oldlist ]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.