Skip to main content
 首页 » 编程设计

python之使用唯一键和所有相关值将列表列表转换为字典

2025年05月04日14mayingbao

我是 Python 新手,目前正在为一个问题而苦恼。我有一个列表列表:

[[0,1], [1,2,8], [3,4], [4,2], [2,5], [5,6,7], [8, 9,10,11,12]]

我的目标是用以下格式从中制作字典:

{0:[1],1:[2,8],2:[8,1,4,5],3:[4],5:[6,7,2],6 :[5,7],7:[5,6],8:[1,2,10,9,11,12],9:[8,10,11,12],10:[8,9, 11,12],11:[12,10,9,8],12:[11,9,10,8]}。

简而言之:

It has to make a dictionary with unique keys from 1 to 12 in this case (all unique numbers in a list), and to each key it assigns a list of values, which is a common subset for this key i.e for key 2 it appears in lists [4,2], [2,5], [1,2,8] so it has to assign to a key 2 a value which is a list of numbers in those 3 lists except 2.

因此键 2 的输出应该是:2:[8,1,4,5] 等等。

我做了一些代码:

data = [[0,1], [1,2,8], [3,4], [4,2], [2,5], [5,6,7], [8,9,10,11,12]] 
 
graph = {} 
for i in range(13): 
    graph[i] = 3 
 
numbers = list(range(0,13)) 
for row in data: 
    for i in graph.keys(): 
        if i in row: 
            graph[i] = row 
 
for key,value in graph.items(): 
    graph[key] = graph[key][1:] 
 
print(graph) 

然而,它给了我输出:

{0: [1], 1: [2, 8], 2: [5], 3: [4], 4: [2], 5: [6, 7], 6: [ 6, 7], 7: [6, 7], 8: [9, 10, 11, 12], 9: [9, 10, 11, 12], 10: [9, 10, 11, 12], 11 : [9, 10, 11, 12], 12: [9, 10, 11, 12]}

我真的不知道如何以这样的方式组合这些列表以获得所需的输出。

请您参考如下方法:

d=dict() 
entries=[] 
for i in range(0,13): 
    entries=[] 
    for j in data: 
        if i in j: 
            entries+=[num for num in j if num!=i] 
    d[i]=entries 

输出

{0: [1], 
 1: [0, 2, 8], 
 2: [1, 8, 4, 5], 
 3: [4], 
 4: [3, 2], 
 5: [2, 6, 7], 
 6: [5, 7], 
 7: [5, 6], 
 8: [1, 2, 9, 10, 11, 12], 
 9: [8, 10, 11, 12], 
 10: [8, 9, 11, 12], 
 11: [8, 9, 10, 12], 
 12: [8, 9, 10, 11]}