欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python實(shí)現(xiàn)list元素按關(guān)鍵字相加減的方法示例

 更新時間:2017年06月09日 08:25:54   作者:JoeBlackzqq  
這篇文章主要介紹了python實(shí)現(xiàn)list元素按關(guān)鍵字相加減的方法,結(jié)合具體實(shí)例形式分析了Python針對list元素遍歷與運(yùn)算相關(guān)操作技巧,需要的朋友可以參考下

本文實(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 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)

運(yùn)行:

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

更多關(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è)計有所幫助。

相關(guān)文章

最新評論