首页 > 解决方案 > 我如何清除列表中的任何内容,除了一件事?(Python)

问题描述

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

标签: pythonlist

解决方案


您可以为此使用列表推导:

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构造函数的东西,这可能会导致未来的其他问题


推荐阅读