comparing all values of a list to regex
Alex Martelli
aleax at aleax.it
Wed Sep 25 06:26:53 EDT 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.
E.g.:
num_matches = [ there.match(item) is not None for item in alist ].count(1)
if num_matches == 0:
againanothernewlist.append(alist)
elif num_matches == 1:
anothetnewlist.append(alist)
elif num_matches == len(alist):
anewlist.append(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.
Alex
More information about the Python-list
mailing list