python - 用户从编号列表输入并返回列表

标签 python list input

我有这个程序,它读取并显示一个列表,用逗号分隔。我也有每个列表编号。我要求用户从该列表中选择一个数字。从他们选择的数字中,我试图返回它附带的实际列表值。由于某种原因,我无法仅返回列表值。

因此,如果我选择“2”(整数)作为输入,它应该返回 Customers。

到目前为止,这是我的代码:

list1 = ['ID', 'Customers', 'Employees', 'Orders']

def display(list1):
    counter = 0
    record = []
    for tables in list1:
        counter += 1
        record.append(tables)
        print("%s. %s" % (counter, tables))
    return record

def get_list(record):
    print("\nPick a number:")
    choose = input()
    choose = int(choose)

    x = []
    if choose in record:
        x.append(record)
        print(x)

record = display(list1)
get_list(record)

最佳答案

您可以改用dict

list1 = ['ID', 'Customers', 'Employees', 'Orders']

def display(list1):
    counter = 0
    record = {}
    for tables in list1:
        counter += 1
        record[counter] = tables
        print("%s. %s" % (counter, tables))
    return record

def get_list(record):
    print("\nPick a number:")
    choose = input()
    choose = int(choose)

    if choose in record:        
        print(record[choose])

record = display(list1)
get_list(record)

输出:

1. ID
2. Customers
3. Employees
4. Orders

Pick a number:
2
Customers

您的 record 变量将如下所示:

{1: 'ID', 2: 'Customers', 3: 'Employees', 4: 'Orders'}

关于python - 用户从编号列表输入并返回列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55898212/

相关文章:

python - 如何像数组一样处理 tf.decode_csv() 中的张量。

python - 使用 Python 中的请求将文件上传到 Google 云端硬盘

python - 在 Python 中存储和访问大型(~10 GB)列表的方法?

php - 为什么我不能将输入类型日期的最小值设置为今天?

jquery - 验证所有表单输入是否具有类别

python - 避免在 sympy 中计算乘以 1

python - 有没有办法将 libgpuarray 与 Intel GPU 一起使用?

python - 删除 Python 列表列表中的重复项

python - 使用包含重复值的列表在 python 中生成字典列表

python - 使用 python xlib 全局捕获、忽略和发送键事件,识别虚假输入