简体   繁体   English

如何查找列表列表中的哪些项目等于另一个列表

[英]How to find which items in list of lists is equal to another list

I have a list of lists that looks like this:我有一个看起来像这样的列表:

[[0],
[0, 1, 2],
[2],
[3],
[4],
[5],
[0, 1, 2, 3, 4, 5, 6, 7],
[7],
[8],
[9],
[8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18],
[11],
[11, 12, 13, 14, 15, 16, 17, 18],
[13],
[14],
[14, 15, 16, 17, 18],
[16, 17, 18],
[17],
[17, 18]]

I am trying to find the least number of items in the list, when concatenated, that equal the full range of the list.我试图在列表中找到最少数量的项目,当连接时,等于列表的整个范围。 In this case, the full range of the list is this:在这种情况下,列表的完整范围是这样的:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]

So in this case, these two items from the list of lists would equal the full range:因此,在这种情况下,列表列表中的这两项将等于整个范围:

[0]
[0, 1, 2]
[2]
[3]
[4]
[5]
---> [0, 1, 2, 3, 4, 5, 6, 7]
[7]
[8]
[9]
---> [8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]
[11]
[11, 12, 13, 14, 15, 16, 17, 18]
[13]
[14]
[14, 15, 16, 17, 18]
[16, 17, 18]
[17]
[17, 18]

One way using itertools.permutations and chain :使用itertools.permutationschain的一种方法:

from itertools import permutations, chain

starget = sorted(target)
for i in range(2, len(target)):
    for perm in permutations(l, i):
        if sorted(chain(*perm)) == starget:
            print(i, perm)
            break
    break

Output: Output:

2 ([0, 1, 2, 3, 4, 5, 6, 7], [8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM