簡體   English   中英

我可以在Python中獲取列表值的總和(不出現索引值)

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

我有一個輸出列表,

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

所以我想獲得每個相同值的總和。 根據此清單,輸出應為

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

我試圖找到一種方法來執行此操作,但仍然找不到正確的方法。 誰能告訴我我能得到預期的輸出嗎?

更靜態的方法。

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'))

此實現符合您的條件,但是正如@ScottHunter所說,存在一些模糊性。

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)

或者,您可以使用collections.Counter如果您希望省略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)

collections使用defaultdict

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)

使用字典

您可以使用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})

如果您不介意使用第3方擴展名,則可以使用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))

打印:

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

1免責聲明:我是該圖書館的作者

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM