I am trying to get the sum of x in this type of list: myList=[[y,x],[y,x],[y,x]
Here is my code I have been trying:
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)
I have run into many problems, but my current problem are listed below:
1. This list is the way I receive it, so the fact that they are all strings I have been trying to change them to floats so that I can the the sum(myList[1]) of each list inside myList.
2. The list ranges from 1 to 100
You can use list comprehension :
total = sum([float(x[1]) for x in myLists])
print(total) # 24391.39
The following will do:
>>> sum([float(x[0]) for x in myLists])
5.997
This should do:
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
I'm unsure where acceptibleBids
comes from in that code, but I'll assume it is a copy of myList
, or something similar to it. The problem with your code is that acceptibleBids[0]
is just ['0.9999', '2423.99000000']
. Similarly, acceptibleBids[1]
is just ['0.9998', '900.00000000']
. So when end up with acceptibleBids0
as [[0.9999, 2423.99000000]]
and acceptibleBids1
is similarly wrong. Then this makes floatList
not be what you wanted it to be.
Edit: list comprehension works too, but I kinda like this way of looking at it. Either way, with list comprehension this would be sum_floats = sum(float([pair[1]) for pair in myLists])
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.