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 + list2for (k, v) in list0:d.setdefault(k, 0) # 设置字典元素初始值d[k] += v # 对字典中的元素按关键字相加ret = list(d.items()) # 字典转换成listret = sorted(ret) # 对list排序return retif __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 + bprint("ret1=", ret1)ret2 = ListAdd(a, b, False) # ret2 = a - bprint("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)]