Skip to main content
 首页 » 编程设计

Python: "if not any"的问题

2025年05月04日16duanxz

我对 Python 函数 any() 有疑问。我想使用 any() 函数从列表中删除任何包含数字的项目。例如:

lst = ['abc123','qwerty','123','hello']

然后我应用以下代码从 lst 中删除项目:'abc123','123'

new_list = [item for item in lst if not any(item.isdigit() for char in item)]

我希望 new_list 只包含项目 ['qwerty','hello'] 但事实证明 new_list=lst...没有变化。为什么?我还尝试使用 import __builtin__ 和 __builtin__.any 但没有成功。我使用 Python 2.7。

请您参考如下方法:

您需要检查 char,而不是 item,在您的 any 中:

new_list = [item for item in lst if not any(char.isdigit() for char in item)] 

或者,您可以使用 re 正则表达式模块:

new_list = [item for item in lst if not re.search(r'\d', item)]