python - 如何使用变量搜索索引?
问题描述
如何设置将打印相应索引号的值的用户输入变量?
这是代码,请帮忙,因为我已经给我的教授发短信和电子邮件两天了,还没有收到回复。
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])
解决方案
你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])
推荐阅读
- php - 如何使用 oauth2 静默登录用户?
- css - 引导容器在中型设备和小型设备上全屏显示,但在大型设备上显示一半
- azure - Azure Linux WebApp 上的 ASP.NET Core NodeServices
- javascript - 用户选择时间后如何使用类星体时间选择器
- svg - 在动画值中重用和组合 SVG 路径 d 字符串
- python - 在 tflite 解释器中分配张量时出错
- ios - 如何在 SpriteKit 中创建适用于多个场景的屏幕控制器?
- c++ - 设置行为异常:本地,还是非本地?
- xml - XSLT / XML 按名称选择值
- kotlin - Kotlin 中的随机数生成器