简体   繁体   中英

Calculating the value of integers in list

I have a list with int values that I would like to add to each other and log the end value. So far I could create a working solution, but it's not so elegant and I would be happy if somebody could show me a smarter solution to achieve the same result.

numberList  = (list(string_dict.values()))
numz = []
placeholder = 0

for x in numberList:
    numz.append(int(x))

for y in numz:
    placeholder = placeholder + y
print (placeholder)

# [1,2,3]   
# result: 6

您可以使用sum函数:

print(sum(int(x) for x in string_dict.values()))

You can take out both loops by using the map() and sum() functions:

numberList  = list(string_dict.values())
numz = []
placeholder = 0

numz = list(map(int, numberList))

placeholder = sum(numz)
print (placeholder)

You don't really need to have numberList and numz in there, though. Just do this:

placeholder = sum(map(int, string_dict.values()))

You can use reduce function also:

from functools import reduce

print reduce( (lambda x, y: x + y), string_dict.values() )

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