我需要减去两个这样的2D列表:
list1= [['some',2],['other',1],['thing',5]]
list2= [['some',1],['thing',5]]
结果应该是这样的:
result= [['some',1],['other',1],['thing',0]]
或
result= [['some',1],['other',1]]
它应该是一个列表,而不是字典;订单并不重要。
答案 0 :(得分:2)
from collections import Counter
list1= [['some',2],['other',1],['thing',5]]
list2= [['some',1],['thing',5]]
c1 = Counter({item[0]: item[1] for item in list1})
c2 = Counter({item[0]: item[1] for item in list2})
result = [[key, value] for key, value in (c1-c2).items()]
result
[['other', 1], ['some', 1]]
答案 1 :(得分:2)
我得到了这样的人:
tmp=[[k,v] for k,v in (Counter(dict(list1)) - Counter(dict(list2))).items()]
Ty伙伴们寻求答案!
答案 2 :(得分:0)
>>> d1, d2 = dict(list1), dict(list2)
>>> d = {key: d1[key] - d2.get(key, 0) for key in d1}
>>> d.items()
[('thing', 0), ('other', 1), ('some', 1)]
>>> map(list, d.items())
[['thing', 0], ['other', 1], ['some', 1]]
答案 3 :(得分:-2)
代码:
list1 = [['some',2], ['other',1], ['thing',5]]
list2 = [['some',1], ['thing',5]]
def list_substractor(l1, l2):
d1 = dict(l1)
d2 = dict(l2)
for key, value in d1.items():
if key in d2.keys():
d1[key] = d1[key] - d2[key]
for item in set( set(d2.keys()) - set(d1.keys())):
d1[item] = -d2[item]
return [[key, value] for key, value in d1.items()]
print list_substractor(list1, list2)
print list_substractor(list2, list1)
输出:
[['thing', 0], ['other', 1], ['some', 1]]
[['thing', 0], ['other', -1], ['some', -1]]