如何添加第二项?

时间:2017-05-10 14:23:04

标签: python

所以,我得到了一个清单:

list2= [['A', '0'], ['B', '1'], ['B', '4'], ['B', '2'], ['B', '0'], ['C', '0'], ['C', '1'], ['C', '2'], ['D', '2'], ['D', '3'], ['D', '0']]

如果子列表中的第一项是相同的,我需要添加第二项。怎么做?

result expected:[['A', 0],['B',7],['C',3],['D',5]]

3 个答案:

答案 0 :(得分:0)

list2= [['A', '0'], ['B', '1'], ['B', '4'], ['B', '2'], ['B', '0'], ['C', '0'],
        ['C', '1'], ['C', '2'], ['D', '2'], ['D', '3'], ['D', '0']]
dict2 = {}
for a, b in list2:
    if dict2.get(a) is None:
        dict2[a] = int(b)
    else:
        dict2[a] += int(b)
rv = [[a, b] for a, b in dict2.items() ]
print(rv)

使用dict存储列表第一项的计数

答案 1 :(得分:0)

使用集合:

from collections import defaultdict
from operator import itemgetter

list2= [['A', '0'], ['B', '1'], ['B', '4'], ['B', '2'], ['B', '0'], ['C', '0'], ['C', '1'], ['C', '2'], ['D', '2'], ['D', '3'], ['D', '0']]

result = defaultdict(int)
for item in list2:
    a, value = item
    result[(a)] += int(value)
print(sorted([[a, total] for a,total in result.items()], key=itemgetter(0)))

答案 2 :(得分:0)

让,

>>> list2
[['A', '0'], ['B', '1'], ['B', '4'], ['B', '2'], ['B', '0'], ['C', '0'], ['C', '1'], ['C', '2'], ['D', '2'], ['D', '3'], ['D', '0']]

是输入

您可以使用来自运算符模块的itemgetter来获取所有字符,而set()将获得唯一元素。

有了这个,您可以遍历list2以匹配每个唯一字符并对结果列表求和!

>>> from operator import itemgetter
>>> [(c,sum([int(val) for st,val in list2 if st==c])) for c in set(map(itemgetter(0),list2))]
[('A', 0), ('C', 3), ('B', 7), ('D', 5)]

分解代码,

>>> map(itemgetter(0),list2)
['A', 'B', 'B', 'B', 'B', 'C', 'C', 'C', 'D', 'D', 'D']
>>> set(map(itemgetter(0),list2))
set(['A', 'C', 'B', 'D'])
>>> [(c,sum([int(val) for st,val in list2 if st==c])) for c in set(map(itemgetter(0),list2))]
[('A', 0), ('C', 3), ('B', 7), ('D', 5)]