Splitting a list of strings
Alex Martelli
aleax at aleax.it
Wed Sep 18 10:09:15 EDT 2002
Sean Ross wrote:
...
> filter, where you drop handfuls of change into the top of the device and
> they come out the other side sorted into pennies, nickels, dimes,
> quarters. In this case I had comments, attributes, and data. The comments
...
> You can probably just chalk this all up to an infatuation with list
> comprehensions.
Yep. A list comprehension is a device that Python got from functional
programming (Haskell, specifically): in functional programming, data
structures don't mutate. Thus, a list comprehension doesn't mutate
existing structures -- it just produces a new one.
For the "change sorter" effect, use a normal loop and a dictionary
of lists. Say you have a function "classifier" that accepts any
item in the list and returns how the item should be classified (as
a number, say, or a string -- any hashables that distinguish item
classifications will do). "Sieving" a list that way is then trivial:
def sieve(alist, classifier):
result = {}
for item in alist:
result.setdefault(classifier(item),[]).append(result)
return result
If you don't want the result as a dictionary of lists, but e.g. a
list of lists in ascending order of classifier-returned keys,
change the last statement to:
keys = result.keys()
keys.sort()
return [result[key] for key in keys]
See, you get to use a list comprehension again in this case:-).
Alex
More information about the Python-list
mailing list