简体   繁体   English

Python:迭代添加列表的相同元素

[英]Python : Adding the same elements of a list iteratively

I have a list of elements as given below- 我有下面列出的元素列表-

[(a,1),(b,2),(c,3),(d,4),(e,5),(f,6),(a,7),(b,8),(c,9),(d,10),(e,11),(f,12)]

I am trying to add the value given next to a letter with a different value given next to the same letter. 我试图将字母旁边的值与相同字母旁边的值相加。

For example- "a" has a value of 1, the program should compare "a" to all the terms in the list until it finds a match. 例如,“ a”的值为1,程序应将“ a”与列表中的所有术语进行比较,直到找到匹配项为止。 Once it finds another term "a" having a value of 7, it should add the two values so that we get a=8. 一旦找到另一个值为7的项“ a”,则应将这两个值相加,从而得出a = 8。

Expected output is- 预期输出为-

a=8, b=10, c=12, d=14, e=16, f=18

The solution you suggest is going to have a complexity of O(n 2 ). 您建议的解决方案的复杂度为O(n 2 )。

You can do it in O(n) by using defaultdict (since it requires a single pass over the entire list): 您可以使用defaultdict在O(n)中完成此操作(因为它需要对整个列表进行一次传递):

from collections import defaultdict

li = [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5), ('f', 6), ('a', 7), ('b', 8), 
      ('c', 9), ('d', 10), ('e', 11), ('f', 12)]

output = defaultdict(int)

for letter, number in li:
    output[letter] += number

print(output)
# defaultdict(<class 'int'>, {'a': 8, 'b': 10, 'c': 12, 'd': 14, 'e': 16, 'f': 18})

This solution of course requires the elements to be hashable, but this can be remedied by using the string representation of the elements if they are not. 当然,此解决方案要求元素是可哈希的,但是可以通过使用元素的字符串表示法来纠正这些问题。

An answer that doesn't utilize the defaultdict. 不使用defaultdict的答案。

_list = [("a",1),("b",2),("c",3),("d",4),("e",5),("f",6),("a",7),("b",8),("c",9),("d",10),("e",11),("f",12)]

tmp = dict()

for k in _list:
    try:
        tmp[k[0]] += k[1]
    except KeyError:
        tmp[k[0]] = k[1]

print(tmp)    

Result: 结果:

{'a': 8, 'b': 10, 'c': 12, 'd': 14, 'e': 16, 'f': 18}

Using itertools.groupby and operator.itemgetter , can be substituted with lambda 使用itertools.groupbyoperator.itemgetter ,可以用lambda代替

from itertools import groupby
from operator import itemgetter

lst = sorted(lst, key=itemgetter(0))
d = {k: sum(i[1] for i in g) for k, g in groupby(lst, key=itemgetter(0))}
# {'a': 8, 'b': 10, 'c': 12, 'd': 14, 'e': 16, 'f': 18}

Dictionary comprehension expanded: 词典理解扩展:

d = {}
for k, g in groupby(lst, key=itemgetter(0)):
    d[k] = sum(i[1] for i in g)
from collections import defaultdict

l = [('a',1),('b',2),('c',3),('d',4),('e',5),('f',6),('a',7),('b',8),('c',9),('d',10),('e',11),('f',12)]

d = defaultdict(int)
for k, v in l:
    d[k] += v

Result: 结果:

defaultdict(<class 'int'>, {'a': 8, 'b': 10, 'c': 12, 'd': 14, 'e': 16, 'f': 18})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM