本文实例讲述了python实现list元素按关键字相加减的方法。分享给大家供大家参考,具体如下:
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 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 + b print("ret1=", ret1) ret2 = ListAdd(a, b, False) # ret2 = a - b print("ret2=", ret2)
运行:
E:/Program/Python>del.pya= [('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)]
希望本文所述对大家Python程序设计有所帮助。
新闻热点
疑难解答