【问题标题】:Obtaining all sub list of list with element in the same order with Python [duplicate]使用Python以相同的顺序获取列表的所有子列表[重复]
【发布时间】:2021-08-08 22:47:11
【问题描述】:

我的问题如下:

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

["a","b","c","d"]

我想在保持元素顺序的同时获得该列表的所有可能长度为 X 的“子列表”。 对于 X=2,它会返回我:

["a","b"]
["a","c"]
["a","d"]
["b","c"]
["b","d"]
["c","d"]

我真的不知道如何开始,任何帮助将不胜感激

【问题讨论】:

    标签: python list


    【解决方案1】:

    您可以使用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']
    

    【讨论】:

      猜你喜欢
      • 2018-10-13
      • 2019-05-18
      • 1970-01-01
      • 1970-01-01
      • 2015-03-26
      • 2011-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多