comparing all values of a list to regex
aleax at aleax.it
Wed Sep 25 12:26:53 CEST 2002
Manuel Hendel wrote:
> I have to compare all values of a list to a regex. If the regex
> matches all list items the list should be added to a new list. If the
> regex matches just one list item, the list should be added to another
> new list. And last but not least, if the regex doesn't mutch at all,
> the list should be added again to another new list.
> Can someone help me with this? This is driving me crazy.
num_matches = [ there.match(item) is not None for item in alist ].count(1)
if num_matches == 0:
elif num_matches == 1:
elif num_matches == len(alist):
Note that there's some ambiguity on what to do if alist is empty --
literally this is BOTH "matches all list items" AND "doesn't match
at all". Here I've chosen the second interpretation, but depending
on your specs you can choose to test num_matches in different ways.
More information about the Python-list