假设我有两个1D列表
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]]
我期待任何输入......现在我将继续尝试!
答案 0 :(得分:5)
>>> firstList = [ "sample01", None, "sample02", "sample03", None ]
>>> secondList = [ "sample01", "sample02", "sample03", None, None, None, "sample04"]
使用列表comp
>>> [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']]