本文實(shí)例講述了python實(shí)現(xiàn)list元素按關(guān)鍵字相加減的方法。分享給大家供大家參考,具體如下:
Python list中的元素按關(guān)鍵字相加或相減:
# coding=utf-8# 兩個list按關(guān)鍵字相加或相減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)   # 設(shè)置字典元素初始值    d[k] += v        # 對字典中的元素按關(guān)鍵字相加  ret = list(d.items())    # 字典轉(zhuǎn)換成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)運(yùn)行:
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)]更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python列表(list)操作技巧總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python Socket編程技巧總結(jié)》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門與進(jìn)階經(jīng)典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設(shè)計有所幫助。
新聞熱點(diǎn)
疑難解答
圖片精選