首页 > 解决方案 > 通过输入的位置重新排列可变大小的列表

问题描述

我需要一些关于如何["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

任何建议表示赞赏:)

标签: pythonlist-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']

推荐阅读