玩蛇网提供最新Python编程技术信息以及Python资源下载!

Python list内元素生成新的组合怎么写

比如l = [1,2,3]
指定长度2,就会得到[1,2][2,3][1,3],不考虑顺序。

生成排列可以用product:

from itertools import product
l = [1, 2, 3]
print list(product(l, l))
print list(product(l, repeat=4))

组合的话可以用combinations:

from itertools import combinations
print list(combinations([1,2,3,4,5], 3))

下面是我以为没有combinations然后自己写的,没有itertools的python(2.6以下)可供参考。

import copy

def combine(l, n): 
    answers = []
    one = [0] * n 
    def next_c(li = 0, ni = 0): 
        if ni == n:
            answers.append(copy.copy(one))
            return
        for lj in xrange(li, len(l)):
            one[ni] = l[lj]
            next_c(lj + 1, ni + 1)
    next_c()
    return answers

print combine([1, 2, 3, 4, 5], 3)

输出:

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

玩蛇网文章,转载请注明出处和文章网址:https://www.iplaypy.com/wenda/wd20308.html

相关文章 Recommend

玩蛇网Python互助QQ群,欢迎加入-->: 106381465 玩蛇网Python新手群
修订日期:2017年05月18日 - 16时50分31秒 发布自玩蛇网

您现在的位置: 玩蛇网首页 > Python问题解答 > 正文内容
我要分享到:

必知PYTHON教程 Must Know PYTHON Tutorials

必知PYTHON模块 Must Know PYTHON Modules