syntax question

A

AF

If I have a list of touples:

l = [(x1, y1), (x2, y2), ...]

Is there a 1 line way to extract and get the sum of each x and y
column. I can do it this way with 2 lines of code and iterating
through the list twice:

sumx = sum([x for x, y in l])
sumy = sum([y for x, y in l])

Is there a 1 liner way to get the sums of both x and y and only
iterate thru the list once?

Also, is there a way to extract a list of x's and a list of y's from
the touple list? 1 line of course.

Thanks!

AF
 
E

Erik Max Francis

AF said:
If I have a list of touples:

l = [(x1, y1), (x2, y2), ...]

Is there a 1 line way to extract and get the sum of each x and y
column. I can do it this way with 2 lines of code and iterating
through the list twice:

sumx = sum([x for x, y in l])
sumy = sum([y for x, y in l])

Is there a 1 liner way to get the sums of both x and y and only
iterate thru the list once?

Also, is there a way to extract a list of x's and a list of y's from
the touple list? 1 line of course.

Use zip:
l = ((1, 2), (3, 4), (5, 6))
zip(*l) [(1, 3, 5), (2, 4, 6)]
xSum, ySum = map(sum, zip(*l))
xSum 9
ySum
12
 
E

Elaine Jackson

L=[(1,2),(10,20),(100,200)]
map(None,*L) [(1, 10, 100), (2, 20, 200)]
sum(map(None,*L)[0])
111

| If I have a list of touples:
|
| l = [(x1, y1), (x2, y2), ...]
|
| Is there a 1 line way to extract and get the sum of each x and y
| column. I can do it this way with 2 lines of code and iterating
| through the list twice:
|
| sumx = sum([x for x, y in l])
| sumy = sum([y for x, y in l])
|
| Is there a 1 liner way to get the sums of both x and y and only
| iterate thru the list once?
|
| Also, is there a way to extract a list of x's and a list of y's from
| the touple list? 1 line of course.
|
| Thanks!
|
| AF
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top