substituting list comprehensions for map()
Steven D'Aprano
steve at REMOVE-THIS-cybersource.com.au
Mon Nov 2 23:04:47 EST 2009
On Mon, 02 Nov 2009 19:19:41 +1100, Ben Finney wrote:
> "Jon P." <jbperez at gmail.com> writes:
>
>> I'd like to do:
>>
>> resultlist = operandlist1 + operandlist2
>
> That's an unfortunate way of expressing it; it's valid Python syntax
> that doesn't do what you're describing (in this case, it will bind
> ‘resultlist’ to a new list that is the *concatenation* of the two
> original lists).
True, but it is valid mathematical syntax if you interpret lists as
vectors. I'm sure there are languages where [1,2]+[3,4] will return
[4,6]. Possibly R or Mathematica?
> Yes, just about any ‘map()’ operation has a corresponding list
> comprehension. (Does anyone know of a counter-example, a ‘map()’
> operation that doesn't have a correspondingly simple list
> comprehension?)
Everyone forgets the multiple argument form of map.
map(func, s1, s2, s3, ...)
would need to be written as:
[func(t) for f in itertools.izip_longest(s1, s2, s3, ...)]
which I guess is relatively simple, but only because izip_longest() does
the hard work.
On the other hand, list comps using an if clause can't be written as pure
maps. You can do this:
[func(x) for x in seq if cond(x)]
filter(cond, map(func, seq))
but the second version may use much more temporary memory if seq is huge
and cond very rarely true.
And I don't think you could write this as a single map:
[func(a, b) for a in seq1 for b in seq2]
--
Steven
More information about the Python-list
mailing list