我是使用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])
我需要在原始列表中搜索所有与重复项列表中相同的项,并将其值相加,但我不确定最好的方法是什么。
[['b', 7],['a', 2],['c', 2]]
? - georg