简体   繁体   中英

how to add up values out of a list with a dictionary inside a list with python

I already tried to do it myself but I get 1 back and I dont know why. I thought i will be 5.

the code:

test_list = []

for i in range(5):
    test_list.append({"number": 1, "name": "Smith"})


for i in range(len(test_list)):
    number_list = []
    number_list.append(test_list[i]["number"]) 


x = sum(number_list)
print(x)

Thanks to you guys i made it work, the fault was that everytime it loped it made number_list = [] again. so in this new code it only makes number_list = [] when i is 0, so only for the first time it loops.

test_list = []

for i in range(5):
    test_list.append({"number": 1, "name": "Smith"})

for i in range(len(test_list)):
    if i == 0:
        number_list = []
    number_list.append(test_list[i]["number"])


x = sum(number_list)
print(x)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM