[英]List Comprehension with sum of elements in a list
我有一個看起來像這樣的列表:
[['State', 'Gas', 'Air', 'Food', 'Party'],
['Alabama', 4802982, 9, 213068.0, 52419.02],
['Alaska', 721523, 3, 31618.0, 663267.26],
['Arizona', 6412700, 11, 144393.0, 113998.3],
['Arkansas', 2926229, 6, 209159.0, 53178.62],
['California', 37341989, 55, 394608.0, 163695.57],
['Colorado', 5044930, 9, 184289.0, 104093.57],
['Connecticut', 3581628, 7, 45744.0, 5543.33],
['Delaware', 900877, 3, 13849.0, 2489.27],
['District of Columbia', 0, 3, 3418.0, 68.34],
['Florida', 18900773, 29, 271024.0, 65754.59],
['Georgia', 9727566, 16, 271920.0, 59424.77],
['Hawaii', 1366862, 4, 9662.0, 10930.98],
['Idaho', 1573499, 4, 98649.0, 83570.08],
['Illinois', 12864380, 20, 305872.0, 57914.38]]
我想創建一個名為 total 的列表,其中包含按此順序排列的數據元素的總和:各州的氣體總和、各州的空氣總和、各州的食物總和和各州政黨的總和。 顯然要避免列表頂部的列名列表以及各州的名稱。 我已經嘗試了多種方法,但到目前為止,這是我認為引導我朝着正確方向前進的原因:
total = [sum(x) for x in statesData[x]]
一種使用zip
和next
一個方法:
it = zip(*statesData[1:])
next(it) # Pop out the state names
["Total", *(sum(i) for i in it)]
Output:
['Total', 106165938, 179, 2197273.0, 1436348.0800000003]
如果可以使用numpy
,這可以用一行代碼解決
data = [['State', 'Gas', 'Air', 'Food', 'Party'],
['Alabama', 4802982, 9, 213068.0, 52419.02],
['Alaska', 721523, 3, 31618.0, 663267.26],
['Arizona', 6412700, 11, 144393.0, 113998.3],
['Arkansas', 2926229, 6, 209159.0, 53178.62],
['California', 37341989, 55, 394608.0, 163695.57],
['Colorado', 5044930, 9, 184289.0, 104093.57],
['Connecticut', 3581628, 7, 45744.0, 5543.33],
['Delaware', 900877, 3, 13849.0, 2489.27],
['District of Columbia', 0, 3, 3418.0, 68.34],
['Florida', 18900773, 29, 271024.0, 65754.59],
['Georgia', 9727566, 16, 271920.0, 59424.77],
['Hawaii', 1366862, 4, 9662.0, 10930.98],
['Idaho', 1573499, 4, 98649.0, 83570.08],
['Illinois', 12864380, 20, 305872.0, 57914.38]]
sum_states = np.sum(np.array(data)[1:,1:].T.astype(np.float16),axis=1)
要使用list-comprehension
解決此問題,使用map(list,zip(*data))
轉置列表列表將是一個好主意
[sum(item[1:]) for item in list(map(list, zip(*data)))[1:]]
顯然要避免列表頂部的列名列表以及各州的名稱。
所以,首先擺脫那些:
numbers = [row[1:] for row in data[1:]]
數據元素的總和 [按列]
所以我們需要做的第一件事是轉置數據以交換列和行,然后我們可以對每一行求和。
transposed = # go check the other answer!
total_gas, total_air, total_food, total_party = [sum(column) for column in transposed]
# Alternate spelling:
# total_gas, total_air, total_food, total_party = map(sum, transposed)
# This works because our function only needs one argument, which is an element
# from the transposed list; and because we are unpacking the resulting `map`
# object right away.
但似乎您的一般潛在問題實際上是“我如何理解列表理解?”。 在這種情況下,請參閱此參考資料。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.