我有一个字典和一个列表
mylist=[('B',), ('D',), ('B', 'D'), ('B', 'J'), ('B', 'P'), ('B', 'M'), ('D', 'J'), ('D', 'P'), ('D', 'M'), ('J', 'P'), ('J', 'M'), ('P', 'M'), ('B', 'D', 'J'), ('B', 'D', 'P'), ('B', 'D', 'M')]
dict={'B': [1, 0, 1, 1], 'D': [1, 1, 0, 1], 'J': [0, 0, 1, 1], 'P': [1, 1, 0, 1], 'M': [1, 0, 0, 1]}
我试图做的是根据列表对字典值求和。我的代码是:
myresult=[]
for k,v in dict.items():
row=sum(v for k, v in dict.items() if k in mylist)
myresult.append(row)
我得到的是[0,0,0,0,0]
预期结果是基于mylist对字典中的各个项求和,并返回类似
的内容。[(1,0,1,1), (1,1,0,1), (2,1,1,2), xxxx]
有谁能帮忙吗?
mylist=[('B',), ('D',), ('B', 'D'), ('B', 'J'), ('B', 'P'), ('B', 'M'), ('D', 'J'), ('D', 'P'), ('D', 'M'), ('J', 'P'), ('J', 'M'), ('P', 'M'), ('B', 'D', 'J'), ('B', 'D', 'P'), ('B', 'D', 'M')]
# change dict to dict_map
dict_map={'B': [1, 0, 1, 1], 'D': [1, 1, 0, 1], 'J': [0, 0, 1, 1], 'P': [1, 1, 0, 1], 'M': [1, 0, 0, 1]}
myresult = []
for item in mylist:
arrays = [dict_map.get(i) for i in item]
sum_list = [sum(x) for x in zip(*arrays)]
myresult.append(sum_list)
print(sum_list)
结果:
[1, 0, 1, 1]
[1, 1, 0, 1]
[2, 1, 1, 2]
[1, 0, 2, 2]
[2, 1, 1, 2]
[2, 0, 1, 2]
[1, 1, 1, 2]
[2, 2, 0, 2]
[2, 1, 0, 2]
[1, 1, 1, 2]
[1, 0, 1, 2]
[2, 1, 0, 2]
[2, 1, 2, 3]
[3, 2, 1, 3]
[3, 1, 1, 3]
函数式编程的一种方法:
from functools import reduce
my_list = [('B',), ('D',), ('B', 'D'), ('B', 'J'), ('B', 'P'), ('B', 'M'), ('D', 'J'), ('D', 'P'), ('D', 'M'),
('J', 'P'), ('J', 'M'), ('P', 'M'), ('B', 'D', 'J'), ('B', 'D', 'P'), ('B', 'D', 'M')]
dic = {'B': [1, 0, 1, 1], 'D': [1, 1, 0, 1], 'J': [0, 0, 1, 1], 'P': [1, 1, 0, 1], 'M': [1, 0, 0, 1]}
def element_wise_sum(l, o):
return [a + b for a, b in zip(l, o)]
res = [reduce(element_wise_sum, [dic[label] for label in labels]) for labels in my_list]
print(res)
[[1, 0, 1, 1], [1, 1, 0, 1], [2, 1, 1, 2], [1, 0, 2, 2], [2, 1, 1, 2], [2, 0, 1, 2], [1, 1, 1, 2], [2, 2, 0, 2], [2, 1, 0, 2], [1, 1, 1, 2], [1, 0, 1, 2], [2, 1, 0, 2], [2, 1, 2, 3], [3, 2, 1, 3], [3, 1, 1, 3]]
您可以使用简单的for循环来迭代主列表,并使用列表推导式获取键和和,如下所示
mylist=[('B',), ('D',), ('B', 'D'), ('B', 'J'), ('B', 'P'), ('B', 'M'), ('D', 'J'), ('D', 'P'), ('D', 'M'), ('J', 'P'), ('J', 'M'), ('P', 'M'), ('B', 'D', 'J'), ('B', 'D', 'P'), ('B', 'D', 'M')]
dict={'B': [1, 0, 1, 1], 'D': [1, 1, 0, 1], 'J': [0, 0, 1, 1], 'P': [1, 1, 0, 1], 'M': [1, 0, 0, 1]}
myresult = []
for i in mylist:
keys = [dict.get(j) for j in i]
summation = [sum(x) for x in zip(*keys)]
myresult.append(tuple(summation))
print(myresult)
示例:https://rextester.com/ANFN30711