如何查找列表列表中的哪些项目等于另一个列表 [英] How to find which items in list of lists is equal to another list

查看:35
本文介绍了如何查找列表列表中的哪些项目等于另一个列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的列表列表:

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]

推荐答案

使用 itertools.permutations chain 的一种方法:

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

输出:

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

这篇关于如何查找列表列表中的哪些项目等于另一个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆