首页 > 解决方案 > 从一个列表输入元素以添加到另一个列表

问题描述

我的 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。任何关于如何做到这一点的简明解决方案将不胜感激!

标签: pythonlistindexingappend

解决方案


#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()

推荐阅读