【问题标题】:How can I print a numbered list using elements from another list? [duplicate]如何使用另一个列表中的元素打印编号列表? [复制]
【发布时间】:2019-04-19 06:57:02
【问题描述】:

我正在尝试使用此列表中的项目生成和打印编号列表:

ItemList = [Item1, Item2, Item3, Item4]

所以,编号列表应该是这样的。

  1. 项目1
  2. 项目2
  3. 项目3
  4. 项目4

然后程序会要求用户选择一个项目。用户将通过输入数字 1 到 4 来选择项目。

然后程序应该将用户选择的项目分配给一个变量,我们称之为 UserChoice。

我尝试了许多不同的方法,将用户的输入分配给列表的索引,但都不起作用。

Item1, Item2, Item3, Item4 = "Item1", "Item2", "Item3", "Item4"

ItemList = [Item1, Item2, Item3, Item4]

这里我不知道如何打印每个项目的实际索引。

OptionsList = for x in ItemList:
                 print(x)

userInput = input("Choose an item by inputting a number 1-4.")

List.index = userInput

UserChoice = List.index

print(UserChoice)

我希望用户通过输入数字 1-4 选择的列表中的项目分配给 userchoice 变量。

为了记录,项目列表的大小会有所不同,所以不能是只规定1-4的代码。它可以是 1-8、1-3、1-5。它可以是各种范围。

【问题讨论】:

标签: python


【解决方案1】:

首先,使用enumerate 打印项目的索引。然后,获取用户输入,减去 1,因为列表是零索引的,然后使用它访问所选元素。

ItemList = ['Item1', 'Item2', 'Item3', 'Item4']

for index, item in enumerate(ItemList, start=1):
    print(index, item)

input_index = int(input('Choose an item by inputting a number 1-{}.\n'.format(len(ItemList))))
user_choice = ItemList[input_index - 1]
print('You chose:', user_choice)

【讨论】:

  • 太棒了!非常感谢!
  • @SimonCrawford 没问题。另外,我对其进行了更改,使其打印出从 1 开始的索引。
  • @Timothy32 我还添加了“\b”。在数字后面加上小数。
  • @Timothy32,为什么我必须在输入之前输入 int ?我在 python 的文档中没有看到这个。有用。我只是好奇为什么常规输入不起作用。
  • @SimonCrawford 列表的索引必须是整数。 input 返回一个字符串。另外,我们不能从字符串中减去 1。我们必须先转换成整数。
【解决方案2】:
# Define menu items
items = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
    'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
# Define format for each line of the menu (indentation of the numbers)
line = "{{: >{}}}. {{}}".format(len(str(len(items))))
# Loop to print all items and their respective number
for i, item in enumerate(items, 1):
    print(line.format(i, item))
# Input from user
number = int(input("Please choose a number: "))
# Print chosen item back to user
print("You have selected: {}".format(items[number - 1]))

这个解决方案本质上是对每一行使用enumeratestring formatting 的循环。您的输出可能如下所示:

 1. a
 2. b
 3. c
 4. d
 5. e
 6. f
 7. g
 8. h
 9. i
10. j
11. k
12. l
13. m
14. n
15. o
16. p
17. q
18. r
19. s
20. t
21. u
22. v
23. w
24. x
25. y
26. z
Please choose a number: 22
You have selected: v

您仍然需要处理一些问题,例如错误的用户输入,例如负数或根本不是数字。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2012-08-24
  • 2020-03-16
  • 2021-02-21
  • 2020-09-25
  • 2019-10-24
  • 1970-01-01
  • 1970-01-01
  • 2015-06-24
相关资源
最近更新 更多