我有以下两个清单:
level = ["a","b","a","c"]
Number = [1,2,1,2]
我只是想知道我是否可以使用Python计算列表级别中每个元素的总和数。所以输出将是两个新的列表x和y:
x = ["a", "b","c"]
y = [2,2,2] (e.g: the total Number for "a" is 1+1=2, etc)
答案 0 :(得分:3)
一种方法是使用defaultdict
:
from collections import defaultdict
d = defaultdict(int)
for k,v in zip(level, frequency):
d[k] += v
另一种方法是使用Counter
:
from collections import Counter
import itertools
d = Counter(itertools.chain.from_iterable(map(itertools.repeat, level, frequency)))
在两种方式中,您都可以将其解压缩到2个列表中,如下所示:
x, y = zip(*d.items())
答案 1 :(得分:2)
您必须为它们创建键映射。
在代码下面,我使用映射创建字典。如果level
中不存在dict
,请检查frequency
与0
其他总和与最后计算的frequency
的总和。
>>> level = ["a","b","a","c"]
>>> frequency = [1,2,1,2]
>>> my_dict = {}
>>> for (l, f) in zip(level, frequency):
... my_dict[l] = my_dict.get(l, 0) + f
...
>>> print my_dict
{'a': 2, 'c': 2, 'b': 2}
>>> print my_dict.values()
[2, 2, 2]
>>> print my_dict.keys()
['a', 'c', 'b']
答案 2 :(得分:1)
如果你不关心x
中的顺序,你可以使用defaultdict
,虽然我确信有更实用的方法来做到这一点
from collections import defaultdict
defdic = defaultdict(int)
for letter, frequency in zip(level, frequency):
defdic[letter] += frequency
x,y = list(defdic.keys()), list(defdic.values())
# or better yet as proposed by Bharel
x, y = zip(*defdic.items())
<强>输出强>:
>>> x
['a', 'b', 'c']
>>> y
[2, 2, 2]