假设我有两个一维列表
firstList = [ "sample01", None, "sample02", "sample03", None ]
secondList = [ "sample01", "sample02", "sample03", None, None, None, "sample04"]
现在我正在寻找 listComprehension 的配方,它将返回 firstList
、secondList
但没有 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/