![](/img/trans.png)
[英]Sum of specific elements of a list based on indexes from another list in python
[英]calculate sum of all unique elements in a list based on another list python
我有两个这样的清单,
a=[['a', 'b', 'c'], ['b', 'c'], ['a', 'd'], ['x']]
b=[[1, 2, 3], [4,5], [6,7], [8]] (the size of a and b is always same)
现在我想用唯一元素的总和创建两个列表,所以最终列表应该看起来像,
a=['a', 'b', 'c', 'd', 'x']
b=[7, 6, 8, 7, 8] (sum of all a, b, d, d and x)
我可以使用 for 循环来做到这一点,但要寻找一些有效的方法来减少执行时间。
不是那么pythonic,但会完成这项工作:
a=[['a', 'b', 'c'], ['b', 'c'], ['a', 'd'], ['x']]
b=[[1, 2, 3], [4,5], [6,7], [8]]
mapn = dict()
for elt1, elt2 in zip(a, b):
for e1, e2 in zip(elt1, elt2):
mapn[e1] = mapn.get(e1, 0) + e2
elts = mapn.keys()
counts = mapn.values()
print(mapn)
print(elts)
print(counts)
您可以按照以下几行使用zip
和collections.Counter
:
from collections import Counter
c = Counter()
for la, lb in zip(a, b):
for xa, xb in zip(la, lb):
c[xa] += xb
list(c.keys())
# ['a', 'b', 'c', 'd', 'x']
list(c.values())
# [7, 6, 8, 7, 8]
这里有一些想法。
首先,要扁平化您的列表,您可以尝试:
a=[['a', 'b', 'c'], ['b', 'c'], ['a', 'd'], ['x']]
b=[[1, 2, 3], [4,5], [6,7], [8]]
要拥有独特的元素,您可以执行以下操作
A = set([item for sublist in a for item in sublist])
但我首先要做的(也许不是更有效)是:
import pandas as pd
import bumpy as np
LIST1 = [item for sublist in a for item in sublist]
LIST2 = [item for sublist in b for item in sublist]
df = pd.DataFrame({'a':LIST1,'b':LIST2})
df.groupby(df.a).sum()
OUTPUT:
归根结底,您将不得不使用两个 for 循环。 我有一个使用zip
和Counter
的单线解决方案。
第一个解决方案仅适用于所有字符串都是单个字符的特定情况,因为它创建一个每个字母的正确编号的字符串,然后获取每个字母的频率。
from collections import Counter
a = [['a', 'b', 'c'], ['b', 'c'], ['a', 'd'], ['x']]
b = [[1, 2, 3], [4,5], [6,7], [8]]
a, b = zip(*Counter(''.join(x*y for al, bl in zip(a, b) for x, y in zip(al, bl))).items())
对于更一般的情况,您可以执行以下操作:
a, b = zip(*Counter(dict(p for al, bl in zip(a, b) for p in zip(al, bl))).items())
您可以使用 zip() 组合列表及其内部列表,然后将元组列表提供给字典构造函数,以获取包含每个字母值的字典列表。 然后将这些字典转换为 Counter 并将它们相加。
a = [['a', 'b', 'c'], ['b', 'c'], ['a', 'd'], ['x']]
b = [[ 1, 2, 3 ], [ 4, 5 ], [ 6, 7 ], [ 8 ]]
from collections import Counter
from itertools import starmap
mapn = sum(map(Counter,map(dict,starmap(zip,zip(a,b)))),Counter())
elts,counts = map(list,zip(*mapn.items()))
print(mapn) # Counter({'c': 8, 'x': 8, 'a': 7, 'd': 7, 'b': 6})
print(elts) # ['a', 'b', 'c', 'd', 'x']
print(counts) # [ 7, 6, 8, 7, 8]
详细解释:
zip(a,b)
将列表组合成子列表对。 例如 (['a','b','c'],[1,2,3]), ...starmap(zip,...)
获取这些列表对,然后合并到字母数字对的子列表中:[('a',1),('b',2),('c',3)], ...map(dict,...)
转换为字典,然后通过map(counter,...)
转换为 Counter object
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.