Python 元组列表的分组求和¶
pythonserver side programmingprogramming更新于 2025/7/16 17:16:17
在本教程中,我们将编写一个程序,将所有具有相同键的值添加到不同的列表中。让我们看一个例子来清楚地理解它。
输入
list_one = [('a', 2), ('b', 3), ('c', 5)]
list_two = [('c', 7), ('a', 4), ('b', 2)]
输出
[('a', 6), ('b', 5), ('c', 12)]
按照给定的步骤解决问题。
- 初始化列表。
- 使用 dict 将第一个列表转换为字典并将其存储在变量中。
- 遍历第二个列表并将相应的值添加到字典中存在的键。
- 打印结果。
示例
# 初始化列表
list_one = [('a', 2), ('b', 3), ('c', 5)]
list_two = [('c', 7), ('a', 4), ('b', 2)]
# 将 list_one 转换为 dict
result = dict(list_one)
# 遍历第二个列表
for tup in list_two:
# 检查 dict 中的键
if tup[0] in result:
result[tup[0]] = result.get(tup[0]) + tup[1]
# 将结果打印为元组列表
print(list(result.items()))
输出
如果您运行上述代码,那么您将获得以下结果。
[('a', 6), ('b', 5), ('c', 12)]
我们可以使用 Counter from collections 来解决上述问题,而无需遍历任何列表。让我们看看。
示例
# 导入 Counter
from collections import Counter
# 初始化列表
list_one = [('a', 2), ('b', 3), ('c', 5)]
list_two = [('c', 7), ('a', 4), ('b', 2)]
# 获取结果
result = Counter(dict(list_one)) + Counter(dict())
# 将结果打印为元组列表
print(list(result.items()))
输出
如果您运行上述代码,那么您将获得以下结果。
[('a', 6), ('b', 5), ('c', 12)]
结论
如果您对本教程有任何疑问,请在评论部分中提及。
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

