如何从 Python 中的列表中过滤项目?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1314314/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I filter items from a list in Python?
提问by Allen S. Rout
I have data naively collected from package dependency lists.
我从包依赖列表中天真地收集了数据。
Depends: foo bar baz >= 5.2
取决于: foo bar baz >= 5.2
I end up with
我结束了
d = set(['foo','bar','baz','>=','5.2'])
I don't want the numerics and the operands.
我不想要数字和操作数。
In Perl I would
在 Perl 中,我会
@new = grep {/^[a-z]+$/} @old
but I can't find a way to e.g. pass remove() a lambda, or something.
但我找不到一种方法,例如通过 remove() 一个 lambda 或其他东西。
The closest I've come is ugly:
我最接近的是丑陋的:
[ item != None for item in [ re.search("^[a-zA-Z]+$",atom) for atom in d] ]
which gets me a map of which values out of the set I want...ifthe order of the set is repeatable? I know that's not the case in Perl hashes.
这让我得到了我想要的集合中哪些值的映射......如果集合的顺序是可重复的?我知道在 Perl 哈希中情况并非如此。
I know how to iterate. :) I'm trying to do it the pythonesque Right Way
我知道如何迭代。:) 我正在尝试以正确的方式做到这一点
回答by Triptych
No need for regular expressions here. Use str.isalpha
. With and without list comprehensions:
这里不需要正则表达式。使用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)
PersonallyI don't think you have to use a list comprehension for everything in Python, but I always get frowny-faced when I suggest map
or filter
answers.
就我个人而言,我认为您不必对 Python 中的所有内容都使用列表理解,但是当我提出建议map
或filter
回答时,我总是皱眉。
回答by Ian Clelland
How about
怎么样
d = set([item for item in d if re.match("^[a-zA-Z]+$",item)])
that gives you just the values you want, back in d (the order may be different, but that's the price you pay for using sets.
这给了你你想要的值,回到 d (顺序可能不同,但这是你使用集合支付的价格。