我有一个列表列表
measurements = [[1,2,3],[1,3,5,6],[4,6,7,8]]
相对于其他列表,我需要从每个列表中检索N个唯一元素。说N =2。结果必须是
result = [[1,2],[5,6],[7,8]]
当然可以有其他组合,但我只需要一个这样的组合。 有办法吗?
答案 0 :(得分:1)
如果您想要唯一的元素,则可以使用集合。 要从列表列表中获取唯一值,请尝试以下操作:
>>> measurements = [[1,2,3],[1,3,5,6],[4,6,7,8]]
>>> result = set(x for l in measurements for x in l)
>>> result
{1, 2, 3, 4, 5, 6, 7, 8}
OR
>>> from itertools import chain
>>> measurements = [[1,2,3],[1,3,5,6],[4,6,7,8]]
>>> print(set(chain(*measurements)))
{1, 2, 3, 4, 5, 6, 7, 8}
答案 1 :(得分:0)
import random
measurements = [[1,2,3],[1,3,5,6],[4,6,7,8]]
result = []
N = 2
for x in measurements:
result.append(random.sample(x,N)
print(result)
答案 2 :(得分:0)
您可以先将列表列表转换为集合列表,然后使用set.difference
对其他集合执行functools.reduce
,从而在每个集合中找到唯一元素:
from functools import reduce
measurements = [[1,2,3],[1,3,5,6],[4,6,7,8]]
sets = list(map(set, measurements))
diffs = [reduce(set.difference, sets[:i] + sets[i+1:], sets[i]) for i in range(len(sets))]
diffs
将变为:
[{2}, {5}, {8, 4, 7}]
然后从N
列表中的每个集合中获取diffs
个项目将变得很简单:
result = []
for diff in diffs:
result.append([])
for _ in range(2): # assuming N = 2
try:
result[-1].append(diff.pop())
except KeyError:
pass
result
将变为:
[[2], [5], [8, 4]]
请注意,您的问题[[1,2],[5,6],[7,8]]
的预期输出是错误的,因为1
和6
都不是唯一的。