Example of how python implements the addition and subtraction of list elements by keyword

  • 2020-06-03 07:06:56
  • OfStack

This article illustrates how python can add and subtract list elements by keyword. To share for your reference, specific as follows:

Elements in Python list are added or subtracted by keywords:

# coding=utf-8
#  two list Add or subtract keywords 
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)   #  Sets the initial value of the dictionary element 
    d[k] += v        #  Add the elements in the dictionary by keyword 
  ret = list(d.items())    #  Dictionary conversion to list
  ret = sorted(ret)      #  right list The sorting 
  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)


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

More about Python related topics: interested readers to view this site "Python list (list) skills summary", "Python data structure and algorithm tutorial", "Python Socket programming skills summary", "Python function using techniques", "Python string skills summary", "Python introduction and advanced tutorial" and "Python file and directory skills summary"

I hope this article has been helpful in Python programming.

Related articles: