python - 指定的列表理解

标签 python list list-comprehension

假设我有两个一维列表

firstList = [ "sample01", None, "sample02", "sample03", None ]
secondList = [ "sample01", "sample02", "sample03", None, None, None, "sample04"]

现在我正在寻找 listComprehension 的配方,它将返回 firstListsecondList 但没有 None 对象。

所以它应该是这样的

listComprehension_List = [  [ "sample01","sample02","sample03" ] ,  [ "sample01","sample02","sample03", "sample04"  ]     ]
listComprehension_List = [[firstList without NONE objects],[secondList without NONE objects]]

我期待任何意见...现在我会继续尝试!

最佳答案

>>> firstList = [ "sample01", None, "sample02", "sample03", None ]
>>> secondList = [ "sample01", "sample02", "sample03", None, None, None, "sample04"]

使用列表组件

>>> [x for x in firstList if x is not None]
['sample01', 'sample02', 'sample03']

或者你可以只使用filter

>>> filter(None, secondList)
['sample01', 'sample02', 'sample03', 'sample04']

对于两者:

>>> [[y for y in x if y is not None] for x in (firstList, secondList)]
[['sample01', 'sample02', 'sample03'], ['sample01', 'sample02', 'sample03', 'sample04']]

关于python - 指定的列表理解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17108975/

相关文章:

python - 权重需要多少字节的内存?

python - 尝试用RSA加密视频帧;解密后得到垃圾而不是原始数据

python - 我的实时搜索实现是否滥用 PyQt5 方法?

r - 将数据框添加到每个列表元素

Python复制列表列表

python - 如何通过 Python socket.send() 发送字符串以外的任何内容

java - Arrays.asList 是否违反了 Liskov 替换原则?

python - 查找列表中子列表项最大值的最佳方法

python - 重新格式化嵌套的元组列表时出现问题?

python - for 循环以在 python 中列出理解或映射