New to Python
Stargaming
stargaming at gmail.com
Mon Mar 12 05:42:50 EDT 2007
Bert Heymans schrieb:
> On Mar 12, 3:02 am, Alberto Vieira Ferreira Monteiro
> <albm... at centroin.com.br> wrote:
>
>>Hi, I am new to Python, how stupid can be the questions I ask?
>>
>>For example, how can I add (mathematically) two tuples?
>>x = (1,2)
>>y = (3,4)
>>How can I get z = (1 + 3, 2 + 4) ?
>>
>>Alberto Monteiro
>
>
>
> Alberto -
>
> List comprehesion, no doubt about it:
>
>>>>z = [k+p for k,p in (x, y)]
>>>>z
>
> [3, 7]
>
> - Bert
>
Since 1+3 is not really (only if you use rally bad approximations) 3
(neither 2+4 is 7!), i'd rather prefer using zip:
>>> x = (1,2)
>>> y = (3,4)
>>> [k+p for k,p in (x,y)] # wrong one
[3, 7]
>>> [k+p for k,p in zip(x,y)] # zip-version
[4, 6]
What your's is doing is unpacking the contents of x first to k and p and
adding them to each other and afterwards doing the same with y's contents.
More information about the Python-list
mailing list