通过输入的位置重新排列可变大小列表

Rearranging a variable size list by an inputted positions

我需要一些关于如何重新排列名称列表的建议,例如 ["A", "B", "C", "D"],使用输入的位置顺序,例如 [3,1,4,2].

问题是名单的大小从 14 不等,位置也是可变的,具体取决于输入。它们的长度是一样的,所以当有3个名字时,位置就有3个值。

在基本的非重排名称列表["A", "B", "C", "D"]中,值的位置:A is 1, B is 2等等。

示例: 非重新排列的名字是 ["Mat", "Bara", "Tom"] 所以 Mat 是 1,Bara 是 2,Tom 是 3

示例: 新位置应为 [3,1,2]

示例: 重新排列的列表将是 ["Tom","Mat","Bara"]

到目前为止,我已经尝试过 names[positions[i]] 和其他一些方法,但没有成功。

这是迄今为止最简单的代码:

num = 0
pos_list = []
name_list = []

num = int(input("how many names:"))
for i in range(num):
    name = input("input name:")
    name_list.append(name)
    pos = int(input("enter the positions that the names should be arranged to:"))
    pos_list.append(pos)

# first name entered is 1, the second name entered is 2 so on...
# now they have to be rearranged by the inputted positions

任何建议表示赞赏:)

使用list comprehension:

names_list = ["A", "B", "C", "D"]
pos_list = [3,1,4,2]
print([names_list[i-1] for i in pos_list])
# ['C', 'A', 'D', 'B']