在作为子集的集合列表中找到集合并选择它们

时间:2018-11-13 10:28:30

标签: python python-3.x set list-comprehension slice

我只想从作为另一个集合的子集的集合列表中选择那些集合,因此本质上是这样:

sets = [{1, 2, 3}, {6, 7, 8}]
s = {1, 2, 3, 4, 5, 6, 7}
list(compress(sets, [sub <= s for sub in sets]))

这有效,但是先评估列表理解然后再使用compress感觉不对。有没有一种方法可以直接索引,例如:

sets[[sub <= s for sub in sets]] ### This does not work!

1 个答案:

答案 0 :(得分:2)

尝试一下:

[i for i in sets if all(j in s for j in i)]

测试:

In [226]: sets = [{1, 2, 3}, {6, 7, 8}, {1,2}, {3}, {7,1}, {7,8}, {8}]
In [227]: s = {1, 2, 3, 4, 5, 6, 7}

In [228]: [i for i in sets if all(j in s for j in i)]
Out[228]: [{1, 2, 3}, {1, 2}, {3}, {1, 7}]