本文实例讲述了python实现list元素按关键字相加减的方法。分享给大家供大家参考,具体如下:
Python list中的元素按关键字相加或相减:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
# 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)
|
运行:
1
2
3
4
5
|
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 )]
|
希望本文所述对大家Python程序设计有所帮助。