我只是想知道是否有一种更动态的方法可以从给定的排列中获取一步变化,而不是指定每一步。我打算做的是,如果我让我们说“(0,0,0,0,0,)”的排列,并且我指定了选择的可能性作为一个范围,所以在这种情况下,我指定了范围为 5,选择为“0,1,2,3,4”,我想生成如下所示的排列: (1,0,0,0,0) , (2,0,0,0,0 ), (3,0,0,0,0) 等等,一次只能更改一个元素,我该怎么做。任何帮助都会很棒!
问问题
386 次
2 回答
2
不完全确定你在找什么......也许是这样的,
def single_element_permutation(given, new):
for i in xrange(len(given)):
for ele in new:
yield given[:i] + (ele,) + given[i+1:]
for e in single_element_permutation((0, 0, 0, 0, 0), range(5)):
print e
输出:
(0, 0, 0, 0, 0)
(1, 0, 0, 0, 0)
(2, 0, 0, 0, 0)
(3, 0, 0, 0, 0)
(4, 0, 0, 0, 0)
(0, 0, 0, 0, 0)
(0, 1, 0, 0, 0)
(0, 2, 0, 0, 0)
(0, 3, 0, 0, 0)
(0, 4, 0, 0, 0)
(0, 0, 0, 0, 0)
(0, 0, 1, 0, 0)
(0, 0, 2, 0, 0)
(0, 0, 3, 0, 0)
(0, 0, 4, 0, 0)
(0, 0, 0, 0, 0)
(0, 0, 0, 1, 0)
(0, 0, 0, 2, 0)
(0, 0, 0, 3, 0)
(0, 0, 0, 4, 0)
(0, 0, 0, 0, 0)
(0, 0, 0, 0, 1)
(0, 0, 0, 0, 2)
(0, 0, 0, 0, 3)
(0, 0, 0, 0, 4)
于 2013-08-28T22:43:01.767 回答
0
>>> from itertools import product
>>> for p in product(range(5), repeat=5):
print(p[::-1])
(0, 0, 0, 0, 0)
(1, 0, 0, 0, 0)
(2, 0, 0, 0, 0)
(3, 0, 0, 0, 0)
(4, 0, 0, 0, 0)
(0, 1, 0, 0, 0)
(1, 1, 0, 0, 0)
....
>>> import itertools
>>> for p in itertools.permutations(range(5)):
print(p[::-1])
(4, 3, 2, 1, 0)
(3, 4, 2, 1, 0)
(4, 2, 3, 1, 0)
(2, 4, 3, 1, 0)
(3, 2, 4, 1, 0)
....
>>> for p in itertools.combinations_with_replacement(range(5), 5):
print(p)
(0, 0, 0, 0, 0)
(0, 0, 0, 0, 1)
(0, 0, 0, 0, 2)
(0, 0, 0, 0, 3)
(0, 0, 0, 0, 4)
(0, 0, 0, 1, 1)
....
像那样?类似的东西?:P
于 2013-08-28T22:40:22.513 回答