【问题标题】:Itertools without repetition and order [duplicate]没有重复和顺序的Itertools [重复]
【发布时间】:2019-10-04 06:10:35
【问题描述】:

假设我有以下列表lst=[1,1,2,2,3,3,4,4,5,5,6,6]。如何使用 itertools 获得 4 个数字的所有可能组合?我的问题是,我想将某些重复项视为相同的子集,例如 [1,1,2,3][1,1,2,3] 相同,即使 1 位于不同的位置,它们代表同一个集合。知道如何进行吗?

我尝试过的示例: listOfCombinations = [x for x in itertools.combination(lst, 5)]

【问题讨论】:

    标签: python itertools


    【解决方案1】:

    您可以考虑为您的结果组合维护一个set,因为set 不允许重复:

    lst = [1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6]
    
    res = set()
    for c in itertools.combinations(lst, 4):
      res.add(c)
    
    print(res)
    # {(2, 5, 6, 6), (2, 4, 4, 6), (2, 4, 4, 5), (1, 4, 4, 5) ...}
    

    或者,正如 @juanpa.arrivillaga 提到的,只是

    res = set(itertools.combinations(lst, 4))
    

    【讨论】:

    • 哇,谢谢。那很容易。直到。
    • 这可以只是res = set(itertools.combinations(lst, 4))
    猜你喜欢
    • 1970-01-01
    • 2015-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-12
    • 1970-01-01
    相关资源
    最近更新 更多