python list中的元素按关键字相加或相减:
# coding=utf-8
# 两个list按关键字相加或相减
def ListAdd(list1, list2, bAdd = True):
if bAdd == False:
list2 = [(k, -v) for (k, v) in list2]
d = {}
list0 = list1 + list2
for (k, v) in list0:
d.setdefault(k, 0) # 设置字典元素初始值
d[k] += v # 对字典中的元素按关键字相加
ret = list(d.items()) # 字典转换成list
ret = sorted(ret) # 对list排序
return ret
if __name__ == '__main__':
a = [("s1", 10), ("s2", 13), ("s3", 25), ("s7", 30)]
b = [("s1", 22), ("s3", 16), ("s10", 8)]
print("a=", a)
print("b=", b)
ret1 = ListAdd(a, b) # ret1 = a + b
print("ret1=", ret1)
ret2 = ListAdd(a, b, False) # ret2 = a - b
print("ret2=", ret2)
运行:
E:\Program\Python>del.py
a= [('s1', 10), ('s2', 13), ('s3', 25), ('s7', 30)]
b= [('s1', 22), ('s3', 16), ('s10', 8)]
ret1= [('s1', 32), ('s10', 8), ('s2', 13), ('s3', 41), ('s7', 30)]
ret2= [('s1', -12), ('s10', -8), ('s2', 13), ('s3', 9), ('s7', 30)]