list comprehention

Paddy paddy3118 at netscape.net
Thu Jan 19 15:50:21 EST 2006


Hi,
I liked the twist at the end when you state that only the first two 2's
count. It reminded me
of my maths O'level revision where you always had to read the question
thoroughly.

Here is what I came up with:

>>> ref
[2, 2, 4, 1, 1]
>>> lst
[2, 2, 5, 2, 4]
>>> tmp = [ [val]*min(lst.count(val), ref.count(val)) for val in set(ref)]
>>> tmp
[[], [2, 2], [4]]
>>> answer = [x for y in tmp for x in y]
>>> answer
[2, 2, 4]
>>>

I took a lot from Peter Ottens reply to generate tmp then flattened the
inner lists.

After a bit more thought, the intermediate calculation of tmp can be
removed with a
little loss in clarity though, to give:

>>> answer = [ val for val in set(ref) for x in range(min(lst.count(val), ref.count(val)))]
>>> answer
[2, 2, 4]



- Cheers,  Paddy.




More information about the Python-list mailing list