gpt4 book ai didi

python - 在列表列表中查找重复项

转载 作者:IT老高 更新时间:2023-10-28 22:23:28 28 4
gpt4 key购买 nike

我正在使用 Python 2.7 并尝试对列表列表进行重复数据删除并合并重复项的值。

现在我有:

original_list = [['a', 1], ['b', 1], ['a', 1], ['b', 1], ['b', 2], ['c', 2], ['b', 3]]

我想匹配每个嵌套列表的第一个元素,然后添加第二个元素的值。我想以这个结尾(最终列表的顺序无关紧要):

ideal_output = [['a', 2], ['b', 7], ['c', 2]]

到目前为止,我有一些代码可以根据每个嵌套列表的第一个元素找到重复值:

for item in original_list:
matches = -1
for x in original_list:
if (item[0] == x[0]):
matches += 1
if matches >= 1:
if item[0] not in duplicates_list:
duplicates_list.append(item[0])

从这里我需要搜索 original_list 中的所有 duplicates_list 项目并将值相加,但我不确定最好的方法是什么。

最佳答案

很多很好的答案,但他们都使用了比我更多的代码,所以这是我的看法,因为它的值(value):

totals = {}
for k,v in original_list:
totals[k] = totals.get(k,0) + v

# totals = {'a': 2, 'c': 2, 'b': 7}

一旦你有了这样的 dict,就可以从这些答案中的任何一个中使用 items 来获取一个(n 个对象,其行为类似于一个)元组列表:

totals.items()
# => dict_items([('a', 2), ('c', 2), ('b', 7)])

并在元组中运行 list 以获得列表列表:

[list(t) for t in totals.items()]
# => [['a', 2], ['c', 2], ['b', 7]]

如果你想要它们按顺序排序:

sorted([list(t) for t in totals.items()])
# => [['a', 2], ['b', 7], ['c', 2]]

关于python - 在列表列表中查找重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19811418/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com