索引Python中的排列列表

时间:2015-03-06 23:13:11

标签: python indexing permutation

此代码生成所有排列的列表:

 def permute(xs, low=0):
    if low + 1 >= len(xs):
        yield xs
    else:
        for p in permute(xs, low + 1):
            yield p        
        for i in range(low + 1, len(xs)):        
            xs[low], xs[i] = xs[i], xs[low]
            for p in permute(xs, low + 1):
                yield p        
            xs[low], xs[i] = xs[i], xs[low]

for p in permute(['A', 'B', 'C', 'D']):
    print p

我想要做的是为排列列表创建一个索引,这样如果我调用一个数字,我就可以访问该特定的排列。

例如:

if index.value == 0:
    print index.value # ['A','B','C','D']
elif index.value == 1:
    print index.value # ['A','B','D','C']
#...

我是Python新手,请提前感谢您提供的任何指导。

4 个答案:

答案 0 :(得分:1)

您还可以创建一个新功能getperm,以便从您的生成器中获取排列index

def getperm(index,generator):
    aux=0
    for j in generator:
        if aux == index:
            return j
        else:
            aux = aux +1

In:  getperm(15,permute(['A', 'B', 'C', 'D']))
Out: ['C', 'A', 'D', 'B']

答案 1 :(得分:0)

迭代器不支持“随机访问”。您需要将结果转换为列表:

perms = list(permute([....]))
perms[index]

答案 2 :(得分:0)

像列维所说,听起来你想要使用字典。 字典看起来像这样:

#permDict = {0:['A', 'B', 'C', 'D'], 1:['A', 'B', 'D', 'C'], ...}

permDict = {}
index = 0
for p in permute(['A', 'B', 'C', 'D']):
    permDict[index] = p
    index += 1

然后根据您指定的密钥获取一个值。

if index == 0:
    print permDict[0] # ['A','B','C','D']
elif index == 1:
    print permDict[1] # ['A','B','D','C']
#...

或者只是将每个排列存储在列表中并调用这些索引。

permList = [p for p in permute(['A', 'B', 'C', 'D'])]
#permList[0] = ['A', 'B', 'C', 'D']
#permlist[1] = ['A', 'B','D', 'C']

答案 3 :(得分:0)

您可以直接生成所需的排列(不经过所有先前的排列):

from math import factorial

def permutation(xs, n):
    """
    Return the n'th permutation of xs (counting from 0)
    """
    xs   = list(xs)
    len_ = len(xs)
    base = factorial(len_)
    assert n < base, "n is too high ({} >= {})".format(n, base)
    for i in range(len_ - 1):
        base //= len_ - i
        offset = n // base
        if offset:
            # rotate selected value into position
            xs[i+1:i+offset+1], xs[i] = xs[i:i+offset], xs[i+offset]
        n %= base
    return xs

然后

>>> permutation(['A', 'B', 'C', 'D'], 15)
['C', 'B', 'D', 'A']