[英]How can I get the sum of all list[1] inside of list of lists items using python 3?
我試圖在這種類型的列表中獲得 x 的總和: myList=[[y,x],[y,x],[y,x]
這是我一直在嘗試的代碼:
myLists = [['0.9999', '2423.99000000'], ['0.9998', '900.00000000'], ['0.9997', '4741.23000000'], ['0.9995', '6516.16000000'], ['0.9991', '10.01000000'], ['0.9990', '9800.00000000']]
if chckList(myLists):
floatList = []
listLength = len(acceptibleBids)
acceptibleBids0 = list(map(float, acceptibleBids[0]))
acceptibleBids1 = list(map(float, acceptibleBids[1]))
floatList.append(acceptibleBids0)
floatList.append(acceptibleBids1)
sumAmounts = sum(amount[1] for amount in floatList)
print(sumAmounts)
print(acceptibleBids)
我遇到了很多問題,但我目前的問題如下:
1. 這個列表是我接收它的方式,所以事實上它們都是字符串,我一直在嘗試將它們更改為浮點數,以便我可以計算 myList 中每個列表的 sum(myList[1])。
2.列表范圍從1到100
您可以使用列表理解:
total = sum([float(x[1]) for x in myLists])
print(total) # 24391.39
以下將做:
>>> sum([float(x[0]) for x in myLists])
5.997
這應該這樣做:
sum = 0
for pair in myLists:
sum+= float(pair[1])
#of course, if there is something that can't
#be a float there, it'll raise an error, so
#do make all the checks you need to make
我不確定該代碼中的acceptibleBids
來自哪里,但我會假設它是myList
的副本,或者類似的東西。 您的代碼的問題是acceptibleBids[0]
只是['0.9999', '2423.99000000']
。 同樣, acceptibleBids[1]
只是['0.9998', '900.00000000']
。 因此,當acceptibleBids0
以[[0.9999, 2423.99000000]]
結束時, acceptibleBids1
同樣是錯誤的。 然后這使得floatList
不是你想要的。
編輯:列表理解也有效,但我有點喜歡這種看待它的方式。 無論哪種方式,對於列表理解,這將是sum_floats = sum(float([pair[1]) for pair in myLists])
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.