简体   繁体   中英

Can I get sum of a list values (not occurrences of index values) in Python

I have an output list like,

[['0'], ['happy', 1], ['happy', 1.5], ['0'], ['sad', 1], ['0'], ['0'], ['happy', 1]]

So I want to get sum of the each same values. According to this list the output should be,

happy weight : 3.5
0 count : 4
sad weight : 1

I tried to find a way to do this and I still fail to find a correct way for that. Can anyone tell me can I get the output as I expected.

The more static way of doing it.

l=[['0'], ['happy', 1], ['happy', 1.5], ['0'], ['sad', 1], ['0'], ['0'], 
['happy', 1]]
print(sum(1 for x in l if x[0]=='0'))
print(sum(x[1] for x in l if x[0]=='happy'))
print(sum(x[1] for x in l if x[0]=='sad'))

This implementation fits your criteria, but as @ScottHunter said, there is some vagueness.

lst = [['0'], ['happy', 1], ['happy', 1.5], ['0'], ['sad', 1], ['0'], ['0'], ['happy', 1]]


def update_count(item_key, increase, dictionary):
    try:
        dictionary[item_key] += increase
    except KeyError:
        dictionary[item_key] = increase

item_counts = dict()
for item in lst:
    size = len(item)
    if size == 1:
        update_count(item[0], 1, item_counts)
    elif size == 2:
        update_count(item[0], item[1], item_counts)
    else:
        print("Too many elements in item!")

print(item_counts)

Or you can use collections.Counter if you prefer to leave out the try/except :

from collections import Counter

lst = [['0'], ['happy', 1], ['happy', 1.5], ['0'], ['sad', 1], ['0'], ['0'], ['happy', 1]]

item_counts = Counter()
for item in lst:
    size = len(item)
    if size == 1:
        item_counts[item[0]] += 1
    elif size == 2:
        item_counts[item[0]] += item[1]
    else:
        print("Too many elements in item!")

print(item_counts)

Using defaultdict from collections :

from collections import defaultdict

lst = [['0'], ['happy', 1], ['happy', 1.5], ['0'], ['sad', 1], ['0'], ['0'], ['happy', 1]]

item_counts = defaultdict(int)  # the int() func returns 0 if key doesn't exist
for item in lst:
    size = len(item)
    if size == 1:
        item_counts[item[0]] += 1
    elif size == 2:
        item_counts[item[0]] += item[1]
    else:
        print("Too many elements in item!")

print(item_counts)
x = [['0'], ['happy', 1], ['happy', 1.5], ['0'], ['sad', 1], ['0'], ['0'], ['happy', 1]]
d = {k: 0 for k in set([i[0] for i in x])}

for i in x:
    if len(i) == 1:
        d[i[0]] += 1
    elif len(i) == 2:
        d[i[0]] += i[1]

for k, v in d.items():
    print(k, v)

using a dict

You can use a Counter :

l = [['0'], ['happy', 1], ['happy', 1.5], ['0'], ['sad', 1], ['0'], ['0'], ['happy', 1]]

from collections import Counter
c = Counter()
for v in l:
    c[v[0]] += 1 if len(v) == 1 else v[1]

print c  # Counter({'0': 4, 'happy': 3.5, 'sad': 1})

If you don't mind using an 3rd party extension, you could use iteration_utilities.groupedby 1 :

lst = [['0'], ['happy', 1], ['happy', 1.5], ['0'], ['sad', 1], ['0'], ['0'], ['happy', 1]]
from iteration_utilities import groupedby

for key, value in groupedby(lst, lambda x: x[0]).items():
    if key == '0':
        print(key, 'count:', len(value))
    else:
        print(key, 'weight:', sum(x[1] for x in value))

which prints:

0 count: 4
happy weight: 3.5
sad weight: 1

1 Disclaimer: I'm the author of that library

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