我如何从清单中清除任何东西? (python)

问题描述 投票:0回答:3

假设我有以下列表:list = ['hello','world','spam','eggs']我想清除该列表中除“世界”以外的所有内容。我该怎么做?

python list
3个回答
4
投票

您可以为此使用列表理解:

l = ['hello','world','spam','eggs']
only = [item for item in l if item  == 'world'] # ['world']

如果要对多个单词进行操作,则可以按以下方式存储过滤器:

l = ['hello','world','spam','eggs']
filters = ['hello', 'world']
only = [item for item in l if item  in filters] # ['hello', 'world']

或者您也可以按以下方式使用filter函数:

l = ['hello','world','spam','eggs']
only = filter(lambda x: x == 'hello', l) # ['hello']

总体上,现在考虑使用类型名称来调用变量,调用list会覆盖list构造函数,这将来可能会导致其他问题


0
投票

另一种解决方案是检查列表中是否存在“世界”。如果没有分配空列表。

list = ['hello','world','spam','eggs']
if 'world' in list:
    list = ['world'] * list.count('world')
else:
    list = []
print(list)

-1
投票
l = ['hello','world','spam','eggs']
l.remove('world')
print(l)
© www.soinside.com 2019 - 2024. All rights reserved.