python实现获取成员所在的多个位置

注:本代码主要是为了实现多个集合之间求并集时的辅助代码,简单的举个例子来说明代码的功能。

约定:例如{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] 。

下面就是实现的代码:

def func(content):
    all_dict = {}
    for d in content:
        for k in d.keys():
            tmp_value = d[k]
            if k in all_dict.keys():
                tmp_values = all_dict[k]
                # 更新成员数
                for i in range(len(tmp_value)):
                    if tmp_value[i] not in tmp_values:
                        tmp_values.append(tmp_value[i])
                all_dict[k] = tmp_values

            if k not in all_dict.keys():
                # 这里需要处理一种情况:如13: [0, 0],某个字典的值有重复的元素。
                tmp_values = []
                for i in range(len(tmp_value)):
                    tmp = tmp_value[i]
                    if tmp in tmp_values:
                        continue
                    tmp_values.append(tmp)
                all_dict[k] = tmp_values

    return all_dict


if __name__ == "__main__":

    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]}
#学习中遇到问题没人解答?小编创建了一个Python学习交流群:153708845
    res = func([d0, d1, d2, d3, d4])
    for key in res:
        print (key, ':', res[key])

输出结果为:

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]
posted @ 2024-05-27 16:19  嗨学编程  阅读(10)  评论(0编辑  收藏  举报