How can I filter items from a list in Python?

前端 未结 2 638
野趣味
野趣味 2020-12-16 16:42

I have data naively collected from package dependency lists.

Depends: foo bar baz >= 5.2

I end up with

 d = set([\'foo\',\'bar\',\'baz\',\'         


        
2条回答
  •  离开以前
    2020-12-16 17:44

    No need for regular expressions here. Use str.isalpha. With and without list comprehensions:

    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)
    

    Personally I 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.

提交回复
热议问题