gpt4 book ai didi

python - 使用Python以相同的顺序获取元素列表的所有子列表

转载 作者:行者123 更新时间:2023-12-04 07:38:44 24 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Get all ordered combinations of list python

(1 个回答)



How to get all possible combinations of a list’s elements?

(29 个回答)


3个月前关闭。




我的问题如下:
对于给定的长度为 L 的列表
例如(L=4):

["a","b","c","d"]
我想在保持元素顺序的同时获得此列表的长度 X 的所有可能的“子列表”。
对于 X=2 它将返回我:
["a","b"]
["a","c"]
["a","d"]
["b","c"]
["b","d"]
["c","d"]
我真的不知道如何开始,任何帮助将不胜感激

最佳答案

您可以使用 itertools.combinations 对于任务:

from itertools import combinations

lst = ["a", "b", "c", "d"]
X = 2

for c in combinations(lst, X):
print(list(c))
打印:
['a', 'b']
['a', 'c']
['a', 'd']
['b', 'c']
['b', 'd']
['c', 'd']

关于python - 使用Python以相同的顺序获取元素列表的所有子列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67607534/

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