如何在Python中获取元组列表中第一个元素的计数和第二个元素的总和?

huangapple go评论132阅读模式
英文:

How to get a count of first elements and sum of second element in a list of tuples in python?

问题

我有一个元组列表,我期望得到一个字典,其中我想要计算第一个元素重复的次数以及所有第二个元素的总和。

例如:-

input_list = [('Skills', 3), ('Wholesome', 3), ('FanArt', 3), ('Clip', 3), ('Skills', 2), ('FanArt', 2)]

期望的输出:

{"Skills": 5, "Wholesome": 3, "FanArt": 5, "Clip": 3}

我期望以一种优化的方式完成这个任务。

我已经尝试过使用简单的for循环进行编程。但我想要使用itertools或一些内置的包。

英文:

I have a list of tuples and I am expecting a dictionary where I want to count number of times the first element is repeated and sum of all the second elements.

For eg :-

input_list = [('Skills', 3), ('Wholesome', 3), ('FanArt', 3), ('Clip', 3), ('Skills', 2), ('FanArt', 2)]

Expected Output :

{"Skills": 5, "Wholesome": 3, "FanArt": 5, "Clip": 3}

I am expecting a optimised way to do this

I have tried it with simple programming with for loops. But I want to use itertools or some built in package.

答案1

得分: 2

以下是您要求的代码部分的翻译:

input_list = [('Skills', 3), ('Wholesome', 3), ('FanArt', 3), ('Clip', 3), ('Skills', 2), ('FanArt', 2)]

output_dict = {}
# 遍历元组值
for k, v in input_list:
    if (k in output_dict): # 如果键存在则增加值
        output_dict[k] += v
    else:
        output_dict[k] = v # 如果键不存在则创建键值对
print(output_dict)
from collections import defaultdict

input_list = [('Skills', 3), ('Wholesome', 3), ('FanArt', 3), ('Clip', 3), ('Skills', 2), ('FanArt', 2)]
output_dict = defaultdict(int)

for key, value in input_list:
    output_dict[key] += value

print(dict(output_dict))
from collections import Counter

input_list = [('Skills', 3), ('Wholesome', 3), ('FanArt', 3), ('Clip', 3), ('Skills', 2), ('FanArt', 2)]

output_dict = Counter()

for key, value in input_list:
    output_dict[key] += value

print(dict(output_dict))

输出

{'Skills': 5, 'Wholesome': 3, 'FanArt': 5, 'Clip': 3} # 适用于上述所有代码
英文:

You can use this

input_list = [('Skills', 3), ('Wholesome', 3), ('FanArt', 3), ('Clip', 3), ('Skills', 2), ('FanArt', 2)]


output_dict = {}
# Looping over tuple value
for k, v in input_list:
    if (k in output_dict): # if key exists then add value
        output_dict[k] += v
    else:
        output_dict[k] = v # if key not exists then key:value
print(output_dict)

You can also use the default list

from collections import defaultdict

input_list = [('Skills', 3), ('Wholesome', 3), ('FanArt', 3), ('Clip', 3), ('Skills', 2), ('FanArt', 2)]
output_dict = defaultdict(int)


for key, value in input_list:
    output_dict[key] += value

print(dict(output_dict))


Counter from collections will also work same as above

from collections import Counter

input_list = [('Skills', 3), ('Wholesome', 3), ('FanArt', 3), ('Clip', 3), ('Skills', 2), ('FanArt', 2)]

output_dict = Counter()

for key, value in input_list:
    output_dict[key] += value

print(dict(output_dict))

Output

{'Skills': 5, 'Wholesome': 3, 'FanArt': 5, 'Clip': 3} # for all above code

答案2

得分: -1

使用排序后的列表:

from itertools import groupby
from operator import itemgetter

input_list = [
    ("Skills", 3),
    ("Wholesome", 3),
    ("FanArt", 3),
    ("Clip", 3),
    ("Skills", 2),
    ("FanArt", 2),
]

# 按每个元组的第一个元素对输入列表进行排序
sorted_list = sorted(input_list, key=itemgetter(0))

# 你也可以使用 lambda 函数作为键
# sorted_list = sorted(input_list, key=lambda x: x[0])

# 使用 groupby 将元组按第一个元素进行分组
grouped_data = groupby(sorted_list, key=itemgetter(0))

# 创建一个字典,其中包含每个分组的第二个元素的总和
result = {key: sum(item[1] for item in group) for key, group in grouped_data}

使用 functools 中的 reduce:

result = reduce(lambda acc, tup: {**acc, tup[0]: acc.get(tup[0], 0) + tup[1]}, input_list, {})

**acc 从 acc 中获取键/值对(与 **kwargs 相同)。

英文:

Using a sorted list:

from itertools import groupby
from operator import itemgetter

input_list = [
    ("Skills", 3),
    ("Wholesome", 3),
    ("FanArt", 3),
    ("Clip", 3),
    ("Skills", 2),
    ("FanArt", 2),
]

# Sort the input list by the first element of each tuple
sorted_list = sorted(input_list, key=itemgetter(0))

# you can also use a lambda function as a key
# sorted_list = sorted(input_list, key=lambda x: x[0])

# Use groupby to group the tuples by the first element
grouped_data = groupby(sorted_list, key=itemgetter(0))

# Create a dictionary with the sums of the second elements for each group
result = {key: sum(item[1] for item in group) for key, group in grouped_data}

Using reduce from functools:

result = reduce(lambda acc, t: {**acc, tup[0]: acc.get(tup[0], 0) + tup[1]}, input_list, {})

**acc gets the key/values pairs from acc(same as **kwargs).

huangapple
  • 本文由 发表于 2023年6月22日 16:58:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/76530179.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定