假设我有以下列表:list = ['hello','world','spam','eggs']
我想清除该列表中除“世界”以外的所有内容。我该怎么做?
您可以为此使用列表理解:
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
构造函数,这将来可能会导致其他问题
另一种解决方案是检查列表中是否存在“世界”。如果没有分配空列表。
list = ['hello','world','spam','eggs']
if 'world' in list:
list = ['world'] * list.count('world')
else:
list = []
print(list)
l = ['hello','world','spam','eggs']
l.remove('world')
print(l)