python - 通过输入的位置重新排列可变大小的列表
问题描述
我需要一些关于如何["A", "B", "C", "D"]
使用输入的位置顺序重新排列名称列表的建议,例如,[3,1,4,2]
。
问题是名单的大小是可变的1
,4
位置也是可变的,基于输入。它们的长度相同,所以当有 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
任何建议表示赞赏:)
解决方案
使用列表理解:
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']
推荐阅读
- javascript - 用 JavaScript 在 HTML 页面上的隐藏元素中存储字符串数组
- python - /admin/login/ 'token' 处的 KeyError
- intellij-idea - Geb DSL 模块在 Intellij 中无法识别
- c# - 在 C# 中解密使用 OpenSSL -nosalt 加密文件的 AES;AES 期望大小为 16 字节的数组 IV?
- ios - Swift 显示应用内购买的促销代码视图没有做任何事情
- amazon-web-services - ElasticBeanstalk eb deploy 命令在 .ebignore Linux 2 上上传虚拟环境文件夹
- javascript - 如何设置是的验证条件?
- ssh - Coral Dev Board Mini - 无法通过 USB 连接,但列出了设备 [Windows]
- r - Can't find RPostgreSQL.so in Mac Big Sur in R
- android - Flutter: display Marker information window upon user's input throws PlatformException