[053]python 递归实现list元素随机组合

xiaoxiao2021-02-28  58

有时程序需求需要将list中的元素进行随机不重复组合,并且组合对是有序的,递归可以很好的解决,不多说,程序如下:

#l为数组,n为n个元素组合 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 #test l = ['1','3','2'] l.sort() print combine(l,2) #result [['1', '2'], ['1', '3'], ['2', '3']]
转载请注明原文地址: https://www.6miu.com/read-1700356.html

最新回复(0)