gpt4 book ai didi

python - 找出所有的方法来决定 list 分为三

转载 作者:行者123 更新时间:2023-12-01 00:24:09 28 4
gpt4 key购买 nike

如标题所示,如何找到一个列表可以分为三个列表的所有方式?例如 1,2,3 将返回

[1, 2, 3]
[1] [2] [3]
[1, 2] [3] [ ]
[1] [2, 3] [ ]
[1, 3] [2] [ ]

我尝试了很多东西,但似乎无法得到它。谢谢!

最佳答案

您可以使用库itertools中的组合

import itertools

my_list = [1, 2, 3]

for i in range(len(my_list)):
print(list(itertools.combinations(my_list, i + 1)))

输出

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

现在您可以添加每个列表的长度并添加缺少的空列表(以完成 3 个列表),瞧 - 您得到了结果

关于python - 找出所有的方法来决定 list 分为三,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58732910/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com