Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I filter items from a list in Python?

Tags:

python

I have data naively collected from package dependency lists.

Depends: 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

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

but I can't find a way to e.g. pass remove() a lambda, or something.

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...if the order of the set is repeatable? I know that's not the case in Perl hashes.

I know how to iterate. :) I'm trying to do it the pythonesque Right Way

like image 535
Allen S. Rout Avatar asked Aug 21 '09 21:08

Allen S. Rout


People also ask

How do you exclude items from a list in Python?

The remove() method removes the first matching element (which is passed as an argument) from the list. The pop() method removes an element at a given index, and will also return the removed item. You can also use the del keyword in Python to remove an element or slice from a list.


2 Answers

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.

like image 144
Ian Clelland Avatar answered Sep 21 '22 19:09

Ian Clelland


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.

like image 28
Kenan Banks Avatar answered Sep 23 '22 19:09

Kenan Banks