Skip to main content
 首页 » 编程设计

Python列表组合

2025年05月04日12haluo1

我有一个列表:

nums = [1, 2, 3, 4] 

我想获得拆分列表 1 - 3 的所有可能性:

[ 
    ( 1, (2, 3, 4) ), 
    ( 2, (1, 3, 4) ), 
    ( 3, (1, 2, 4) ), 
    ( 4, (1, 2 ,3) ) 
] 

现在我能找到的最好的方法是使用 itertools.combinations(num, 3),但它只会给出每个项目的第二部分,即 [(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]。我可以使用其他方法吗?

请您参考如下方法:

根据您要解决的问题的普遍性,解决方案可能或多或少简单:)

In [1]: nums = [1, 2, 3, 4] 
 
In [2]: [(x, tuple(y for y in nums if y != x)) for x in nums] 
Out[2]: [(1, (2, 3, 4)), (2, (1, 3, 4)), (3, (1, 2, 4)), (4, (1, 2, 3))] 

如果列表中有重复值,使用索引进行比较:

In [3]: [(x, tuple(y for j, y in enumerate(nums) if j != i)) for i, x in enumerate(nums)] 
Out[3]: [(1, (2, 3, 4)), (2, (1, 3, 4)), (3, (1, 2, 4)), (4, (1, 2, 3))]