[英]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.