![](/img/trans.png)
[英]How to unfold a python dictionary with lists as values into a list of key-value tuples with two elements?
[英]How to flatten the value (list of lists of tuples) of a key in Python dictionary?
我在 python 中有一個字典,看起來像這樣:
{(-1, 1): (0, 1),
(0, 0): [([([(1, 0), (0, 1)], (0, 1))], (1, 0))],
(0, 1): [([([((-1, 1), (0, 2))], (1, 1))], (0, 0))],
(0, 2): (0, 1)}
我不希望它有所有這些額外的括號和圓括號。 這是我用來創建這本字典的代碼:
if condition1==True:
if condition2==True:
if (x,y) in adjList_dict: ##if the (x,y) tuple key is already in the dict
##add tuple neighbours[i] to existing list of tuples
adjList_dict[(x,y)]=[(adjList_dict[(x,y)],neighbours[i])]
else:
adjList_dict.update( {(x,y) : neighbours[i]} )
我只是想創建一個字典,其中鍵是元組,每個鍵的值是一個元組列表。
例如我想要這個結果: (0, 0): [(1, 0), (0, 1), (0, 1), (1, 0)]
我可以展平輸出還是應該在創建字典時更改某些內容?
您可以使用遞歸,然后測試實例是否是一個包含 int 值的簡單元組,例如:
sample = {(-1, 1): (0, 1),
(0, 0): [([([(1, 0), (0, 1)], (0, 1))], (1, 0))],
(0, 1): [([([((-1, 1), (0, 2))], (1, 1))], (0, 0))],
(0, 2): (0, 1)}
def flatten(data, output):
if isinstance(data, tuple) and isinstance(data[0], int):
output.append(data)
else:
for e in data:
flatten(e, output)
output = {}
for key, values in sample.items():
flatten_values = []
flatten(values, flatten_values)
output[key] = flatten_values
print(output)
>>> {(-1, 1): [(0, 1)], (0, 0): [(1, 0), (0, 1), (0, 1), (1, 0)], (0, 1): [(-1, 1), (0, 2), (1, 1), (0, 0)], (0, 2): [(0, 1)]}
您可以使用帶有字典理解的遞歸方法:
d = {(-1, 1): (0, 1),
(0, 0): [([([(1, 0), (0, 1)], (0, 1))], (1, 0))],
(0, 1): [([([((-1, 1), (0, 2))], (1, 1))], (0, 0))],
(0, 2): (0, 1)}
def flatten(e):
if isinstance(e[0], int):
yield e
else:
for i in e:
yield from flatten(i)
{k: list(flatten(v)) for k, v in d.items()}
輸出:
{(-1, 1): [(0, 1)],
(0, 0): [(1, 0), (0, 1), (0, 1), (1, 0)],
(0, 1): [(-1, 1), (0, 2), (1, 1), (0, 0)],
(0, 2): [(0, 1)]}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.