python怎么生成list的所有元素的组合
PHP中文网
PHP中文网 2017-04-17 11:13:56
[Python讨论组]

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

PHP中文网
PHP中文网

认证高级PHP讲师

全部回复(1)
黄舟

生成排列可以用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]]
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号