【问题标题】:Manually keying in a number for list indices in python在 python 中手动键入列表索引的数字
【发布时间】:2013-08-28 13:36:41
【问题描述】:

我有一个文件名列表 例如。文件名=['blacklisted.txt', 'abc.txt', 'asfafa.txt', 'heythere.txt']

我想让用户手动选择要显示的文件名,例如,

*

print "Please key in the first log file you would like to use: "
choice1=raw_input()
print"Please key in the second log file you would like to use: "
choice2=raw_input()
filename1=filenames[choice1]
filename2=filenames[choice2]
print filename1
print filename2

*

但是,我得到了错误: 文件名1=文件名[选择1] TypeError: 列表索引必须是整数,而不是 str。

有什么建议吗?谢谢!

【问题讨论】:

  • choice1=int(raw_input()),使用int()

标签: python list indices


【解决方案1】:

你必须首先使用int()将输入转换为int

print "Please key in the first log file you would like to use: "
choice1=raw_input()
.
.
filename1=filenames[int(choice1)]
.

或者您可以将输入直接转换为 int

choice1 = int(raw_input())
filename1 = filenames[choice1]

您还应该显示文件列表及其相应的索引号,以便用户知道选择哪个。

更新

对于错误处理,您可以尝试类似

while True:
    choice1 = raw_input('Enter first file name index: ')
    if choice1.strip() != '':
        index1 = int(choice1)
        if index1 >= 0 and index1 < len(filenames):
            filename1 = filenames[index1]
            break // this breaks the while loop when index is correct

choice2 也一样

【讨论】:

  • 您可能希望将其包装在 try/except while 循环中以清理输入/重新提示用户。如果用户输入的值不能被强制转换为 int,这可能会引发 TypeError,如果他们输入的值超出列表的范围,则会引发 IndexError,并且您可能不希望程序在这些情况下崩溃。
  • @SilasRay 可能会进行不同的检查以避免错误和索引问题,但答案是针对 OP 所要求的最小解决方案
  • 非常感谢各位的帮助!解决了问题!会听取您的建议和错误处理!
猜你喜欢
  • 2020-10-22
  • 2021-09-17
  • 2013-09-08
  • 2019-03-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-03
  • 1970-01-01
相关资源
最近更新 更多