如何返回多维二维列表中的重复项?

2024-03-29 14:54:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个多维二维的列表。基本上,我想创建一个变量,每行都有重复项,然后我想创建另一个变量,每行都没有重复项。这可以通过使用列表来完成吗?你知道吗

df = [[[2, 3, 3, 3, 7, 8, 9, 9],[3, 3, 3, 5, 9, 9, 10, 11],[3, 3, 3, 4, 9, 9, 13, 15]],
      [[2, 3, 3, 3, 4, 4, 5, 6],[4, 4, 5, 7, 7, 7, 8, 10],[4, 4, 6, 7, 7, 7, 9, 11],[3, 3, 3, 4, 4, 8, 11, 12]],
      [[4, 6, 7, 7, 7, 9, 11, 11],[3, 3, 3, 5, 9, 10, 11, 11],[3, 3, 3, 6, 7, 7, 7, 10, 12, 12]]]

我希望我的结果是:

Dup = [[[3,9],[3, 9],[3, 9]],[[3, 4],[4, 7],[4, 7,[3, 4]],[[7, 11],[3, 11],[3, 7, 12]]]

Not in = [[[2 7, 8],[5,10, 11],[4, 13, 15]],[[2, 5, 6],[5,8, 10],[6, 9, 11],[8, 11, 12]],[[4, 6, 9],[5, 9, 10],[6,10]]]


Tags: indf列表notdup
3条回答

不需要额外的导入,只需使用双嵌套列表理解setcount

>>> [[[x for x in set(ll) if ll.count(x) > 1] for ll in l] for l in df]
[[[3, 9], [3, 9], [3, 9]],
 [[3, 4], [4, 7], [4, 7], [3, 4]],
 [[7, 11], [3, 11], [3, 7, 12]]]

>>> [[[x for x in set(ll) if ll.count(x) == 1] for ll in l] for l in df]
[[[2, 7, 8], [5, 10, 11], [4, 13, 15]],
 [[2, 5, 6], [5, 8, 10], [6, 9, 11], [8, 11, 12]],
 [[4, 6, 9], [5, 9, 10], [6, 10]]]

不过,请注意,如果最内部的列表非常大,那么使用^{}可能会更快;否则就不重要了,这个版本可能是最直接、最容易阅读的。你知道吗

这可以使用列表理解和collections.Counter实现,如下所示:

dup = [[[i for i, c in Counter(sl).items() if c>1] for sl in l] for l in df]
not_in = [[[i for i, c in Counter(sl).items() if c==1] for sl in l] for l in df]

仅供参考,我使用了lsl相应的列表和子列表。i表示项,csl中该项的计数。结果如下:

#duplicates
[[[3, 9], [3, 9], [3, 9]], [[3, 4], [4, 7], [4, 7], [3, 4]], [[7, 11], [3, 11], [3, 7, 12]]]
#uniques
[[[2, 7, 8], [5, 10, 11], [4, 13, 15]], [[2, 5, 6], [5, 8, 10],[6, 9, 11], [8, 11, 12]], [[4, 6, 9], [5, 9, 10], [6, 10]]]
Dup = [[list(dict.fromkeys([el for i, el in zip(range(len(l)), l) if el in l[:i]+l[i+1:]])) for l in ll] for ll in df]
Not_in = [[[el for i, el in zip(range(len(l)), l) if el not in l[:i]+l[i+1:]] for l in ll] for ll in df]

相关问题 更多 >