python - 从一个列表输入元素以添加到另一个列表
问题描述
我的 Python 之旅还很早,所以我的编码知识非常基础。简单的答案表示赞赏。
我的挑战是创建一个函数来从列表中选择一个项目以添加到另一个列表
这是一般思想的伪代码:
# My Lists
list1 = ["item1", "item2", "item3", "item4", "item5"]
list2 = []
# print verticle, indexed list
for element in (list1):
print(list1.index(element) + 1, element)
# create function to input selected item an add to list2
def selectitem():
selection = input("Enter the number of item you'd like to add to list2: ")
if selection == "1": # How would I now define "1" to select and append index 0 from list1 to list2?
list2.append(selection)
我希望这很清楚。总之,如果我在输入中输入“1”,我想将索引 0 添加到 list2。任何关于如何做到这一点的简明解决方案将不胜感激!
解决方案
#My Lists
list1 = ["item1", "item2", "item3", "item4", "item5"]
list2 = []
#create function to input selected item an add to list2
def selectitem():
selection = int(input("Enter the number of item you'd like to add to list2: "))
list2.append(list1[selection-1])
print(list2)
selectitem()
推荐阅读
- r - 如何使用正则表达式在 r 中选择数据框的列?
- javascript - 错误:“无法创建没有数据的 Google 图表!” 当数据加载到 aync Angular 服务中时
- python - 我想提取字符串中的最后一个数字
- ios - 为什么我的从数据库中提取信息的函数不起作用?
- reactjs - 无法设置状态下的axios数据
- javascript - 当我使用多个for循环时,Javascript中的长度错误
- java - Java Reactor 中嵌套 flatMaps 的好习惯是什么?
- c++ - 创建 OpenGL 对象期间的错误
- ios - Firebase 会自动加密密码吗?
- python - 为什么我的 Keras 模型在我加载后会进行训练,即使我实际上并没有提供任何新的训练数据?