简体   繁体   English

如何使用Python 2中的旧列表创建包含特定项目的新列表?

[英]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.

相关问题 如何使用python从列表中选择特定项目并保存在新列表中 - how do I choose specific items from a list using python and save in a new list 我如何从现有列表中创建一个列表(新),其中列表(新)的项目将在 python 中列出 - How can i create a list (new) from an existing list where items of list(new) will be list in python 如何从 python 的列表中 select 特定项目? - How do I select specific items from a list in python? 如何打印 python 列表中的特定项目? - How do I print specific items from a python list? 使用旧列表中的已复制项目和平均项目创建新列表 - Create new list with copied and averaged items from old list Python从列表项中获取特定信息并创建新的列表项 - Python taking specific information from list item and create new list items 从旧列表创建新列表 - Create new list from old list 如何在Python中为特定键创建列表作为字典条目? - How do I create a list as a dictionary entry for a specific key in Python? Python:如何使用原始列表中的某些按字母顺序排列的项目创建新列表? - Python: How to create new list with certain alphabetized items from original list? 如何从列表中删除相同的项目并在Python中对其进行排序? - How do I remove identical items from a list and sort it in Python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM