注:本代码主要是为了实现多个集合之间求并集时的辅助代码,简单的举个例子来说明代码的功能。
约定:例如{11: [2, 3]}表示数据11在集合2和集合3中都存在。
现有以下数据:
d0 = {38: [2], 11: [2, 3], 22: [2, 3]}
d1 = {11: [0, 0, 1, 3], 13: [0, 0], 22: [0, 0, 3], 14: [0, 0, 1, 3]}
d2 = {32: [1, 1], 35: [1, 1], 11: [1, 1, 3], 14: [1, 1, 3], 23: [1, 1]}
d3 = {33: [3], 66: [3], 11: [3], 14: [3], 22: [3], 55: [3]}
d4 = {38: [2], 11: [2, 3], 22: [2, 3], 13: [0, 0], 14: [0, 0, 1, 3], 32: [1, 1], 35: [1, 1], 23: [1, 1], 33: [3], 66: [3], 55: [3]}
那么所有的元素所在的集合为:
38: [2], 11: [2, 3, 0, 1], 22: [2, 3, 0], 13: [0], 14: [0, 1, 3], 32: [1], 35: [1], 23: [1], 33: [3], 66: [3], 55: [3] 。
下面就是实现的代码:
1 # encoding: utf-8 2 3 def func(content): 4 all_dict = {} 5 for d in content: 6 for k in d.keys(): 7 tmp_value = d[k] 8 if k in all_dict.keys(): 9 tmp_values = all_dict[k] 10 # 更新成员数 11 for i in range(len(tmp_value)): 12 if tmp_value[i] not in tmp_values: 13 tmp_values.append(tmp_value[i]) 14 all_dict[k] = tmp_values 15 16 if k not in all_dict.keys(): 17 # 这里需要处理一种情况:如13: [0, 0],某个字典的值有重复的元素。 18 tmp_values = [] 19 for i in range(len(tmp_value)): 20 tmp = tmp_value[i] 21 if tmp in tmp_values: 22 continue 23 tmp_values.append(tmp) 24 all_dict[k] = tmp_values 25 26 return all_dict 27 28 29 if __name__ == "__main__": 30 31 d0 = {38: [2], 11: [2, 3], 22: [2, 3]} 32 d1 = {11: [0, 0, 1, 3], 13: [0, 0], 22: [0, 0, 3], 14: [0, 0, 1, 3]} 33 d2 = {32: [1, 1], 35: [1, 1], 11: [1, 1, 3], 14: [1, 1, 3], 23: [1, 1]} 34 d3 = {33: [3], 66: [3], 11: [3], 14: [3], 22: [3], 55: [3]} 35 d4 = {38: [2], 11: [2, 3], 22: [2, 3], 13: [0, 0], 14: [0, 0, 1, 3], 32: [1, 1], 35: [1, 1], 23: [1, 1], 33: [3], 66: [3], 55: [3]} 36 37 res = func([d0, d1, d2, d3, d4]) 38 for key in res: 39 print (key, ':', res[key])
输出结果为:
1 38 : [2] 2 11 : [2, 3, 0, 1] 3 22 : [2, 3, 0] 4 13 : [0] 5 14 : [0, 1, 3] 6 32 : [1] 7 35 : [1] 8 23 : [1] 9 33 : [3] 10 66 : [3] 11 55 : [3]