0

我有一个文件名列表, 例如。文件名=['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

*

但是,我得到了错误:filename1=filenames[choice1] TypeError: list indices must be integers, not str.

有什么建议吗?谢谢!

4

1 回答 1

0

您必须首先使用将输入转换为 intint()

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一样

于 2013-08-28T13:40:51.280 回答