Python how to get sum of numbers in a list that ha

2019-05-21 00:49发布

问题:

I have a dict,

d = {'a': [4,'Adam', 2], 'b': [3,'John', 4], 'c': [4,'Adam', 3], 'd': [4,'Bill', 3], 'e': [4,'Bob'], 'f': [4, 'Joe'], 'g': [4, 'Bill']}

Is there any quick way to get a sum of the numbers in each of the lists in the dictionary?

For example, a should return 6, b should return 7, so on.

Currently, I am doing this.

for i in d:
    l2=[]
    for thing in d[i]:
        if type(thing) == int:
            l2.append(thing)
        print sum(l2)

Possible for a quicker fix than having to go through each time and append the numbers to a list?

Thanks!

回答1:

Here is a fairly straight forward way using a dictionary comprehension:

sums = {k: sum(i for i in v if isinstance(i, int)) for k, v in d.items()}

Or on Python 2.6 and below:

sums = dict((k, sum(i for i in v if isinstance(i, int))) for k, v in d.items())

Example:

>>> {k: sum(i for i in v if isinstance(i, int)) for k, v in d.items()}
{'a': 6, 'c': 7, 'b': 7, 'e': 4, 'd': 7, 'g': 4, 'f': 4}


回答2:

In this case, since the numbers are all in the 1st and 3rd positions of the lists

>>> {k: sum(v[::2]) for k,v in d.items()}
{'a': 6, 'c': 7, 'b': 7, 'e': 4, 'd': 7, 'g': 4, 'f': 4}


回答3:

If you want to output as a list, use a list comprehension:

d = {'a': [4,'Adam', 2], 'b': [3,'John', 4], 'c': [4,'Adam', 3], 'd': [4,'Bill',
3], 'e': [4,'Bob'], 'f': [4, 'Joe'], 'g': [4, 'Bill']}

sums = [sum(i for i in v if isinstance(i, int)) for k, v in d.items()]

[6, 7, 7, 4, 7, 4, 4]

As you can see this doesn't quite match up. Manually adding the items in d gives

[6, 7, 7, 7, 4, 4, 4]

So why the mismatch?

It's because dictionaries are unsorted

As soon as you create d as a dictionary, it rearranges its items, and therefore outputting such a list comprehension will give you the correct sums, but you don't know which sum corresponds to which dictionary item.

This is why F.J.'s dictionary comprehension suggestion seems the best option here.

Unless you see it is workable with the list comprehension somehow?



回答4:

If your dictionary having float values then the above code will not work, You will get output as 0 value.

So, For handling integers and float, you can use below code.

In comprehension way,

sums = {k: sum(i for i in v if not isinstance(i, str)) for k, v in d.items()}

OR

You can use common function to check whether the given input is number or not then we can sum the values,

d = {'a': [4,'Adam', 2], 'b': [3,'John', 4], 'c': [4,'Adam', 3], 'd': [4,'Bill', 3], 'e': [4,'Bob'], 'f': [4, 'Joe'], 'g': [4, 'Bill']}


def get_num(str):
    """ 
        This function converts the number/number string into a float. Otherwise, returns 0        
     """
    try:
        return float(str)
    except:
        return 0.0

if __name__ == '__main__':
    # example list which contains numbers and strings
    sums = {k:sum(get_num(value) for value in v) for k, v in d.items()}
    print sums
    ## output for the given input dict d
    ## {'a': 6.0, 'c': 7.0, 'b': 7.0, 'e': 4.0, 'd': 7.0, 'g': 4.0, 'f': 4.0}