简体   繁体   中英

Is there a more efficient way of extracting a partial sum from a given number of dictionary values?

I have a dictionary in the format key:("string", int) that I am iterating through from different starting positions.

A number of things are successfully happening with each iteration, however, I would like to pull out a sum of the integer values for the whole dictionary and a sum of the integer values from the beginning of the dictionary to the 'starting position'.

Is there a way to do this through a comprehension as I have done with the total_sum or is this already the most efficient way to accomplish this?

Thank you.

CODE:

fruit_dict = {
    "a":("apple", 64),
    "b":("pear", 100),
    "c":("orange", 44),
    "d": ("lettuce", 4930),
    "e": ("blueberries", 37),
    "f": ("tomatoes", 75)
}

start = 2  # this is the starting position

lst_fruit_dict = list(fruit_dict)[start:]

total_sum = sum(v[1] for k, v in fruit_dict.items())

partial_sum = 0

for i in lst_fruit_dict:  # Partial Sum calculator (the bit I am trying to get more efficient)
    partial_sum += fruit_dict[i][1]

sum(x[1] for x in list(fruit_dict.values())[start:])

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