如何接受Python中枚举列表的输入



所以我有一个列表,我想使用enumerate((对其进行编号,然后让用户使用相应的编号从列表中选择一个项目。有办法做到这一点吗?

(这是一个坏代码,但希望你能知道我想做什么(

print("Which house do you want to sell")
for number,address in enumerate(market['addresses'], 1):
print(number, '->', address)
userSell = input("> ")
if userSell in enumerate(market['addresses']):
print(f"Sold {address}")
else:
print("Address not found...")

IIUC,您可以使用输入的数字直接为您的列表编制索引:

print("Which house do you want to sell")
for number,address in enumerate(market['addresses'], 1):
print(number, '->', address)
userSell = int(input("> "))-1 # you might need a loop/check here to ask again on incorrect input
try:
# assuming market['addresses'] is a list
print(f"Sold {market['addresses'][userSell]}")
except IndexError:
print("Address not found...")

验证用户输入总是一个好主意,尤其是当您需要数值时。

如果你在这种情况下这样做,就没有必要在用户输入后查找地址,因为你已经验证了它

market = {'addresses': ['1 Main Road', '2 Long Street', '100 Pall Mall']}
addresses = market['addresses']
print("Which house do you want to sell?")
for number, address in enumerate(addresses, 1):
print(number, '->', address)
while True:
try:
userSell = int(input("> "))
if 0 < userSell <= len(addresses):
break
raise ValueError('Selection out of range')
except ValueError as ve:
print(ve)
print(f'Sold {addresses[userSell-1]}')

输出:

Which house do you want to sell?
1 -> 1 Main Road
2 -> 2 Long Street
3 -> 100 Pall Mall
> 2
Sold 2 Long Street

用户输入无效:

Which house do you want to sell?
1 -> 1 Main Road
2 -> 2 Long Street
3 -> 100 Pall Mall
> 0
Selection out of range
> 4
Selection out of range
> foo
invalid literal for int() with base 10: 'foo'
> 1
Sold 1 Main Road

尝试更改

if userSell in enumerate(market['addresses']):

if userSell in range(1, len(market['addresses'])):

这将循环遍历末尾地址范围(索引(中的值。

要使原始代码按预期工作,我认为您还需要将用户输入转换为int类型并减去1,因为您在打印选项时指定了start=1

market= {'addresses': ["This Street", "That Street"]}
print("Which house do you want to sell")
for number,address in enumerate(market['addresses'], 1):
print(number, '->', address)
userSell = int(input("> ")) - 1
if userSell in range(len(market['addresses'])):
print(f"Sold {address}")
else:
print("Address not found...")

必须减去1才能使输入与选项匹配,这感觉不是很健壮,因为在代码稍后查找列表中的元素时,您必须记住调整索引。最好存储已编号的选项,然后再引用同一个对象。转换为dict使代码美观、可读、易懂。

market= {'addresses': ["This Street", "That Street"]}
numbered_options = dict(enumerate(market['addresses'], 1))
print("Which house do you want to sell")
for number,address in numbered_options.items():
print(number, '->', address)
userSell = int(input("> "))
if userSell in numbered_options:
print(f"Sold {numbered_options[userSell]}")
else:
print("Address not found...")

不过,我真正建议的是,使用许多预先构建的库中的一个来显示选项列表,并在命令行中从用户那里获得选择。您可以从本线程中提到的选项中进行选择,并查阅库文档来实现它们。没有必要重做别人已经为你做过的事情。

最新更新