2024-04-25 01:17:12 发布
网友
我只是想知道是否有一种更为动态的方法来从给定的排列中获得一个步骤的变化,而不是指定每一个步骤。我计划做的是,如果我有一个排列,比如“(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)以此类推,一次只能更改一个元素,我该怎么做。任何帮助都太好了!在
你完全不确定你在找什么。。。也许像这样
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
输出:
>>> 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
你完全不确定你在找什么。。。也许像这样
输出:
^{pr2}$像那样?沿着这条线的东西??:P
相关问题 更多 >
编程相关推荐