首页 > 解决方案 > 如何使用变量搜索索引?

问题描述

如何设置将打印相应索引号的值的用户输入变量?

这是代码,请帮忙,因为我已经给我的教授发短信和电子邮件两天了,还没有收到回复。

fileName = input("Enter the name of the file, e.g. 'numbers.txt': ")

#Coutning number of lines
lineCount=0
with open(fileName, 'r') as userData:
    for i in userData:
        lineCount=lineCount+1

#converting index count to match linecount
blankIndex = [None]
userList = [blankIndex] + [userData]

print(lineCount)

while True:
    inputTarget = int(input("Enter the number of the line you wish to see, or press enter twice to exit: "))
    if inputTarget == "":
        print("Enjoy your data.  Goodbye!")
        break
    elif inputTarget == 0:
        print("Great, you broke it...*slow clap*")
        break
    else:
        print(userList[inputTarget])

标签: pythonlist

解决方案


while循环中的东西看起来大多不错。问题是,您并没有首先填充列表!

fileName = input("Enter the name of the file, e.g. 'numbers.txt': ")

# we don't need to know the number of lines
# we can just open the file and put it into a list of lines with `.readlines()`
with open(fileName, 'r') as f:
    userList = [None] + f.readlines()
    # alternatively, the following commented-out code is a long-form way to accomplish essentially the same thing:
    # userList = []
    # for line in f:
    #    userList.append(line)

使用这种方法,我们现在可以将userList其视为 - 一个字符串列表,它与文件中的行完全对应(为了使其 1-indexed 而不是 0-indexed,我们添加None为第一个元素,就像你一样'重新尝试在您的代码段中执行)。给定一个索引,我们可以取出该索引处的字符串。

while True:
    try:
        inputTarget = int(input("Enter the number of the line you wish to see, or press enter twice to exit: "))
    except ValueError: # this is the correct way to handle not-a-number inputs  print("Enjoy your data. Goodbye!")
        break
    if inputTarget == 0:
        print("Great, you broke it...*slow clap*")
        break
    else:
        print(userList[inputTarget])

推荐阅读