用Python反转排列


问题内容

我是编程新手,我正在尝试编写Python函数以使用以下代码在{1,2,3,…,n}上查找排列的逆:

def inv(str):
    result = []
    i = list(str).index(min(list(str)))
    while min(list(str)) < len(list(str)) + 1:
        list(str)[i : i + 1] = [len(list(str)) + 1]
        result.append(i + 1)
    return result

但是,当我尝试使用该函数时,inv('<mypermutation>')返回[]。我想念什么吗?Python是否由于某种我不理解的语法原因跳过了while循环?我的Google和stackoverflow搜索都没有返回任何有用的主题。


问题答案:

如果只需要逆排列,则可以使用

def inv(perm):
    inverse = [0] * len(perm)
    for i, p in enumerate(perm):
        inverse[p] = i
    return inverse

perm = [3, 0, 2, 1]
print(inv(perm))
for i in perm:
    print(inv(perm)[i])

[1, 3, 2, 0]
0
1
2
3