[英]How to return unique values from list of pairs?
I have a list of pairs given as: 我有一个成对的列表,如下所示:
a = [[0, 1], [1, 3], [2, 1], [3, 1]]
I would like to return unique matches as a new list for all numbers inside 'a'. 我想返回唯一匹配项作为“ a”内所有数字的新列表。 As an example, I'd like to create something like below - ie where I can select any number from 'a' and see all other numbers associated with it from all of the pairs.
举例来说,我想创建如下所示的内容-即我可以从“ a”中选择任何数字,并从所有对中查看与其相关的所有其他数字。 The list of lists, b, below is an example of what I'd like to achieve:
下面的列表b是我想要实现的示例:
b = [ [0,[1]] , [1,[0,2,3]] , [2,[1]] , [3,[1]] ]
I am open to more efficient/better ways of displaying this. 我愿意展示更有效/更好的方式。 The example above is just one way that came to mind.
上面的示例只是想到的一种方法。
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()]
In case if your list contains lists with different length: 如果您的列表包含长度不同的列表:
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}
To get exact output you ask for use: 要获得准确的输出,您需要使用:
c = [[key, list(value)] for key, value in b.items()]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.