如何在python中减去两个2D列表?

如何在python中减去两个2D列表?,python,list,Python,List,我需要像这样细分两个2D列表: list1= [['some',2],['other',1],['thing',5]] list2= [['some',1],['thing',5]] result= [['some',1],['other',1],['thing',0]] 结果应如下所示: list1= [['some',2],['other',1],['thing',5]] list2= [['some',1],['thing',5]] result= [['some',1],['o

我需要像这样细分两个2D列表:

list1= [['some',2],['other',1],['thing',5]]

list2= [['some',1],['thing',5]]
result= [['some',1],['other',1],['thing',0]]
结果应如下所示:

list1= [['some',2],['other',1],['thing',5]]

list2= [['some',1],['thing',5]]
result= [['some',1],['other',1],['thing',0]]

result= [['some',1],['other',1]]

它应该是一个列表,而不是一本字典;顺序不重要。

我得到的是这样的人:

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]]
tmp=[[k,v] for k,v in (Counter(dict(list1)) - Counter(dict(list2))).items()]
有人在找答案

代码:

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]]

到目前为止你试过什么吗?给我们看一些要讨论的代码。你可以在中直接翻转一个操作数,然后得到答案。这里有3张向下的票,前面的问题有3张向上的票。奇怪的至少测试代码一次。明显可见的语法错误。你应该解释你发布的代码。