代码之家  ›  专栏  ›  技术社区  ›  Padraic Cunningham

使用itertools从列表中获取所有组合

  •  0
  • Padraic Cunningham  · 技术社区  · 12 年前

    我正在处理Euler项目的一个问题,我需要获得在列表中添加int元素的所有组合,

    from itertools import combinations
    evenAbs = [12, 18, 20, 24, 30,36]
    evenCombs =  sorted(([i+j for i,j in combinations(evenAbs, 2)]))
    

    我的问题是,我需要组合包括12+1218+18等。。 我该怎么做?

    1 回复  |  直到 12 年前
        1
  •  2
  •   falsetru    12 年前

    使用 itertools.combinations_with_replacement :

    >>> import itertools
    >>> list(itertools.combinations_with_replacement([1,2,3], 2))
    [(1, 1), (1, 2), (1, 3), (2, 2), (2, 3), (3, 3)]