[英]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.