简体   繁体   English

我可以在Python中获取列表值的总和(不出现索引值)

[英]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. 此实现符合您的条件,但是正如@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)

Or you can use collections.Counter if you prefer to leave out the try/except : 或者,您可以使用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)

Using defaultdict from collections : 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)

using a dict 使用字典

You can use a Counter : 您可以使用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 : 如果您不介意使用第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))

which prints: 打印:

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

1 Disclaimer: I'm the author of that library 1免责声明:我是该图书馆的作者

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在python中将sum用于列表中的特定值? - How can I use sum in python for specific values in a list? 返回一个列表,该列表具有最高的数字总和和值之和的索引 - Return a list with index of highest sum of numbers and the sum of the values python 如何获取列表中最大值的索引,然后使用最大值的索引从另一个列表中打印值? - How can I get the index of max values in list and then print the values from another list with max's index? 如何计算dicts列表中值的出现次数? - How can I count occurrences of values in a list of dicts? Python:如何用元组中的值替换多次出现的字符串 - Python: How can I replace multiple occurrences of a string with values in tuple 总和索引0值匹配的列表值? - Sum list values where index 0 values match? 如何获取 python 中的字典列表中的键值列表? - How can I get list of values of keys in list of dicts in python? 计算值字典列表python的出现次数 - Count the number of occurrences for values dictionary list python 如何使用python将所有索引值的总和加到numpy ndarray的每个元素中? - How can I add to each element of a numpy ndarray the sum of all its index values with python ? 如何通过将其他列表的值用作第一个列表的索引,将一个列表的值插入到另一个列表中? (Python) - How can I insert values of one list into another by using the values of the other lists an index into the first? (Python)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM