'Is there any faster way to add the component in list? Maybe a loop?
I want to add the last component in individual list. Doing it manually from addition operator is easy for small data set. Is there any alternative method which i can use to add those components for over 1000 of lists?
data=[
[514.8,526.9,512,525,27942414],
[527.9, 528.5, 507.15, 510.8, 19353195],
[510 ,522.2 ,504.8 ,520.85 ,21799071],
[519.95, 523.2, 512, 515.7 ,18364451],
[510.4 ,513.85 ,494.25 ,501.85 ,17946821],
]
sum_volume=(data[0][4]+data[1][4]+data[2][4]+data[3][4]+data[4][4])
print(sum_volume)
Solution 1:[1]
Yes you can "transpose" your list, so the last column (4) would be the last list:
sum(list(zip(*data))[-1])
The part zip(*data) zips each list with each other. What zip does is:
list(zip([1, 2], [3, 4]))
[(1, 3), (2, 4)]
Or for your data:
list(zip(*data))
[(514.8, 527.9, 510, 519.95, 510.4),
(526.9, 528.5, 522.2, 523.2, 513.85),
(512, 507.15, 504.8, 512, 494.25),
(525, 510.8, 520.85, 515.7, 501.85),
(27942414, 19353195, 21799071, 18364451, 17946821)]
I use list(zip()) because zip will return an iterable object (<zip>). You can also choose to put it in a tuple, or in a for loop.
So when you unpack your data, your new rows (list indices) are the old columns.
In this case I selected the last column,[-1] but that is equal to [4] in your case.
fourth_column = list(zip(*data))[4]
Solution 2:[2]
You can use list comprehension and slice. -1 means first from last.
sum_volume = sum([d[-1] for d in data])
This equivalent to:
last_components = []
for d in data:
last_components.append(d[-1])
sum_volume = sum(last_components)
Solution 3:[3]
This is a basic way to do that, Also easy to understand.
sum_volume=0
data=[
[514.8,526.9,512,525,27942414],
[527.9, 528.5, 507.15, 510.8, 19353195],
[510 ,522.2 ,504.8 ,520.85 ,21799071],
[519.95, 523.2, 512, 515.7 ,18364451],
[510.4 ,513.85 ,494.25 ,501.85 ,17946821],
]
for i in range(len(data)):
sum_volume+=data[i][4]
print(sum_volume)
There is another way
data=[
[514.8,526.9,512,525,27942414],
[527.9, 528.5, 507.15, 510.8, 19353195],
[510 ,522.2 ,504.8 ,520.85 ,21799071],
[519.95, 523.2, 512, 515.7 ,18364451],
[510.4 ,513.85 ,494.25 ,501.85 ,17946821],
]
sum_volume = sum([i[4] for i in data])
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | omae |
| Solution 3 |
