python實現獲取成員所在的多個位置

嗨学编程發表於2024-05-27

注:本程式碼主要是為了實現多個集合之間求並集時的輔助程式碼,簡單的舉個例子來說明程式碼的功能。

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

相關文章