如何从列返回列表的所有子集?

2024-04-26 06:05:56 发布

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

我有一个列表a = [A,B,C,D]
Concatenated_valuesdf中的列表列。如何获取列a中存在的列表Concatenated_values的所有子集?你知道吗

Concatenated_values 

[B,C]

[A,B,C,D] 

[B,C,D]

[P,Q,R,S,T]

[C,D]

Tags: df列表子集valuesconcatenated
2条回答

a和列表项转换为集合,并使用^{}和布尔索引:

set_a = set(a)
df[df.Concatenated_values.apply(lambda x: set(x).issubset(set_a))]

结果:

  Concatenated_values
0              [B, C]
1        [A, B, C, D]
2           [B, C, D]
4              [C, D]

注意:issubset接受任何iterable作为参数,因此也可以使用set(x).issubset(a),但我发现a到集合的显式转换更清晰,可能更有效。你知道吗

看看itertools.combinations

itertools.combinations(iterable, r)

Return r length subsequences of elements from the input iterable.

Combinations are emitted in lexicographic sort order. So, if the input iterable is sorted, the combination tuples will be produced in sorted order.

您可以将所有列表串联成一个列表,然后获得所有组合。你知道吗

相关问题 更多 >