如何在python中编写一个函数来获取数组的一个permuation

时间:2017-09-06 09:27:50

标签: python permutation

下面的代码给出了数组的所有排列,我想编写一个可以一次使用一个排列的函数(我想一次处理一个排列,例如[2,3,5,4,1] ,6]没有事先生成它们,能够在目标函数中使用它)

s = np.array([1, 2, 3, 4, 5, 6])
from itertools import permutations
for s_temp in permutations(s):
    print (s_temp)

1 个答案:

答案 0 :(得分:1)

你有几个可能性,从permutations开始返回一个迭代器,这样你的代码就可以通过更改print来完成你需要调用的任何内容。

from itertools import permutations
def process(s):
    for s_temp in permutations(s):
        call_your_stuff(s_temp)

此外,如果您拥有排列对象,则可以调用next上的下一个项目:

from itertools import permutations
s = permutations(range(3))
s
<itertools.permutations object at 0x000000000377CFC0>
next(s)
(0, 1, 2)

如果您想为每个排列处理相同的功能,只需使用map,只需将示例中的lambda函数替换为您需要调用的内容:

s = permutations(range(3))
map(lambda (x, y, z): x+y-z, s)
[-1, 1, -1, 3, 1, 3]

您可以将数据收集到列表中以供进一步处理:

s = list(permutations(range(3))) 
s
[(0, 1, 2), (0, 2, 1), (1, 0, 2), (1, 2, 0), (2, 0, 1), (2, 1, 0)]

请注意,如果您在使用排列对象迭代器时没有收集数据(进入列表,元组等),那么数据将“丢失”(您将不得不重新计算)