substituting list comprehensions for map()

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Tue Nov 3 00:31:51 EST 2009


On Mon, 02 Nov 2009 20:06:51 -0800, Anh Hai Trinh wrote:

>> 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?)
> 
> Try turning this into a list comprehension:
> 
>   vectorsum = lambda *args: map(sum, zip(*args))
> 
>   vectorsum([1,2], [3,4], [5,6])
> ->[9, 12]
>   vectorsum([1,2], [3,4], [5,6], [7,8])
> ->[16, 20]

[sum(t) for t in zip(*args)] will do it.

>>> args = [1,2], [3,4], [5,6]
>>> [sum(t) for t in zip(*args)]
[9, 12]
>>> args = [1,2], [3,4], [5,6], [7,8]
>>> [sum(t) for t in zip(*args)]
[16, 20]



-- 
Steven



More information about the Python-list mailing list