Python - Select 基于索引号的列表中的字符串 - 通过输入输入的索引号

Python - Select string from a list based on index number - index number entered via input

我正在尝试帮助某人从列表中提取设施列表,而无需输入设施的全名。相反,我认为将数字与每个设施相关联并允许用户仅输入相应的数字以获取字符串会更容易。例如,如果我有一个 'facility a'、'facility b' 和 'facility c' 的列表,如果用户输入“0”,则会显示 'facility a',1 'facility b' 会出现,等等。我知道我的代码不正确,但我正在努力根据用户通过输入命令输入的数字来完成这项工作。请参阅下面的代码。

facilities = ['facility a', 'facility b', 'facility c']

for count, value in enumerate(facilities):
    j = (count, value)
    print(j) #This is just so the user can see all possible options in the list 

f = input('Please enter the corresponding number of the facility you want to select: ')

final_facility = facilities[f] # I know this doesn't work and it wants a number, not a string

print(final_facility)

使用 int 将输入转换为整数,如下所示:

f = int(input('Please enter the corresponding number of the facility you want to select: '))

准确的说,每当你想访问索引处的元素时,int(f)而不是直接传递f

默认情况下,input() returns 一个字符串。但是,列表索引不能是字符串。所以,它需要像这样

f = int(input('Please enter the corresponding number of the facility you want to select: '))

或者,您可以自动将您的输入类型转换为: f = int(input('Please ...'))

facilities = ['facility a', 'facility b', 'facility c']

for count, value in enumerate(facilities):
    j = (count, value)
    print(j) #This is just so the user can see all possible options in the list

f = input('Please enter the corresponding number of the facility you want to select: ')

final_facility = facilities[int(f)] # Pass int(f) instead of f

print(final_facility)

facilities = ['facility a', 'facility b', 'facility c']

for count, value in enumerate(facilities):
    j = (count, value)
    print(j) #This is just so the user can see all possible options in the list

f = int(input('Please enter the corresponding number of the facility you want to select: ')) # Typecast your input to int

final_facility = facilities[f] 

print(final_facility)

确保处理 ValueErrors 异常。

在最后的设施之前,写f=int(f) 那应该解决它。因为,用户输入默认是 python 中的字符串,所以现在,我们已经将 f 类型转换为解决它的整数。 也可以尝试使用字典,这将完全消除这个麻烦。 同样为了得到答案,在 for 循环之后你可以直接写: print(facilities (int(f))).

您需要检查输入是否为数字,然后将其转换为 int。像这样:

facilities = ['facility a', 'facility b', 'facility c']

for count, value in enumerate(facilities):
    j = (count, value)
    print(j) #This is just so the user can see all possible options in the list 

f = input('Please enter the corresponding number of the facility you want to select: ')

final_facility = 'Please eneter a number' # Prints this if f is not numeric
if f.isnumeric():
    final_facility = facilities[int(f)] # I know this doesn't work and it wants a number, not a string

print(final_facility)