python 组合_python怎么生成list的所有元素的组合

生成排列可以用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]]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值