gpt4 book ai didi

python - Python中List的组合项

转载 作者:行者123 更新时间:2023-11-30 23:34:10 24 4
gpt4 key购买 nike

我有一个 list :

[0, 1, 2, 3, 4, 5]

我想将第一项与除最后一项之外的所有其他项合并。结果应该是一个列表,如下所示:

[[0], [0,1], [0,2], [0,3], [0,4], [0,1,2], [0,1,3] [0,1, 4], [0,2,3], [0,2,4], [0,3,4], [0,1,2,3], [0,1,2,4], [0, 2,3,4], [0,1,2,3,4]]

我该怎么做?谢谢!

最佳答案

import itertools

a = [0, 1, 2, 3, 4, 5]

base = (a[0],)
items = a[1:-1]
combos = [base + combo for length in range(len(items)+1) for combo in itertools.combinations(items, length)]

# In case it matters that the sublists are lists rather than tuples:
combos = [list(combo) for combo in combos]

print combos
# [[0], [0, 1], [0, 2], [0, 3], [0, 4], [0, 1, 2], [0, 1, 3], [0, 1, 4], [0, 2, 3], [0, 2, 4], [0, 3, 4], [0, 1, 2, 3], [0, 1, 2, 4], [0, 1, 3, 4], [0, 2, 3, 4], [0, 1, 2, 3, 4]]

关于python - Python中List的组合项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18334906/

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