[英]How to return unique values from list of pairs?
我有一個成對的列表,如下所示:
a = [[0, 1], [1, 3], [2, 1], [3, 1]]
我想返回唯一匹配項作為“ a”內所有數字的新列表。 舉例來說,我想創建如下所示的內容-即我可以從“ a”中選擇任何數字,並從所有對中查看與其相關的所有其他數字。 下面的列表b是我想要實現的示例:
b = [ [0,[1]] , [1,[0,2,3]] , [2,[1]] , [3,[1]] ]
我願意展示更有效/更好的方式。 上面的示例只是想到的一種方法。
from collections import defaultdict
a = [[0, 1], [1, 3], [2, 1], [3, 1]]
c = defaultdict(set) # default dicts let you manipulate keys as if they already exist
for item in [[0, 1], [1, 3], [2, 1], [3, 1]]:
# using sets avoids duplicates easily
c[item[0]].update([item[1]])
c[item[1]].update([item[0]])
# turn the sets into lists
b = [[item[0], list(item[1])] for item in c.items()]
如果您的列表包含長度不同的列表:
from collections import defaultdict
a = [[0, 1], [1, 3], [2, 1], [3, 1]]
b = defaultdict(set)
for items in a:
for item in items:
b[item] |= set(items) ^ {item}
要獲得准確的輸出,您需要使用:
c = [[key, list(value)] for key, value in b.items()]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.