使用列表推导从Python列表中移除元素
为什么下面这个列表里的数字4没有被移除呢?
>>> list=[1,2,3,4]
>>> [list.remove(item) for item in list if item > 2]
[None]
>>> list
[1, 2, 4]
另外,我想做的是,如果在listB
中找到了某个项目,就把它从listA
中移除。我该如何用列表推导式来实现这个呢?
还有,我该怎么做:
list2=["prefix1","prefix2"]
[item for item in list if not "item starts with a prefix in list2"] # pseudocode
1 个回答
4
首先,仅仅为了副作用使用列表推导式是不好的做法。你应该使用
lst = [x for x in lst if x <= 2]
另外,不要把 list
当作变量名,因为这个名字已经被内置的列表占用了。还有,你的方法不奏效是因为你在遍历列表的同时修改了它。
下面是你方法发生了什么的演示:
# python interpreter
>>> lst = [1,2,3,4]
>>> for item in lst:
... print(item)
... if item > 2:
... lst.remove(item)
... print(lst)
...
1
[1, 2, 3, 4]
2
[1, 2, 3, 4]
3
[1, 2, 4]
如你所见,item
永远不会是 4
。
至于你的第二个问题:
我想做的是,如果
listB
中找到了某个项,就从listA
中删除它。我该如何用列表推导式做到这一点?
bset = set(listB)
listA = [x for x in listA if x not in bset]
至于你的第三个问题:
>>> list1=['prefix1hello', 'foo', 'prefix2hello', 'hello']
>>> prefixes=['prefix1', 'prefix2']
>>> [x for x in list1 if not any(x.startswith(prefix) for prefix in prefixes)]
['foo', 'hello']
请现在停止添加新问题,如果有不同的问题可以开一个新问题,谢谢。