python - 如何从 Python 列表中过滤项目?

标签 python

我天真地从包依赖列表中收集了数据。

取决于:foo bar baz >= 5.2

我结束了

 d = set(['foo','bar','baz','>=','5.2'])

我不需要数字和操作数。

在 Perl 中我会

@new = grep {/^[a-z]+$/} @old

但我找不到方法,例如向 remove() 传递一个 lambda 或其他东西。

我最接近的是丑陋的:

[ item != None for item in [ re.search("^[a-zA-Z]+$",atom)   for atom in d] ]

这让我得到了我想要的集合中哪些值的映射...如果集合的顺序是可重复的?我知道 Perl 哈希不是这种情况。

我知道如何迭代。 :) 我正在尝试以 pythonesque 的正确方式来做

最佳答案

这里不需要正则表达式。使用 str.isalpha .有和没有列表理解:

my_list = ['foo','bar','baz','>=','5.2']

# With
only_words = [token for token in my_list if token.isalpha()]

# Without
only_words = filter(str.isalpha, my_list)

个人 我认为您不必对 Python 中的所有内容都使用列表理解,但当我建议使用 map 时,我总是皱着眉头过滤答案。

关于python - 如何从 Python 列表中过滤项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1314314/

相关文章:

python - 如何手动更改 IAM 角色凭证?

python - 如何间接调用 Jinja2 模板中的宏?

python - 删除重复行和原始行 - Pandas

Python字符串编码方法

python - 如何在 Python 中优雅地创建双向 for 循环?

python - django.core.exceptions.FieldError : Cannot resolve keyword 'timestamp' into field

python - 从数据中提取年份

python - Python 中客户端/服务器未接收数据

python - 自定义域路由到 Flask 服务器,自定义域始终显示在地址栏中

python - fseek(fp, 0, SEEK_CUR) 的副作用是什么