Eri*_*ric 8 python typeerror python-2.7 python-3.x
像标题所说的那样得到错误.这是追溯.我知道lst [x]导致了这个问题,但不太确定如何解决这个问题.我已经搜索了谷歌+ stackoverflow但没有得到我正在寻找的解决方案.
Traceback (most recent call last):
File "C:/Users/honte_000/PycharmProjects/Comp Sci/2015/2015/storelocation.py", line 30, in <module>
main()
File "C:/Users/honte_000/PycharmProjects/Comp Sci/2015/2015/storelocation.py", line 28, in main
print(medianStrat(lst))
File "C:/Users/honte_000/PycharmProjects/Comp Sci/2015/2015/storelocation.py", line 24, in medianStrat
return lst[x]
TypeError: '_io.TextIOWrapper' object is not subscriptable
Run Code Online (Sandbox Code Playgroud)
这是实际的代码
def medianStrat(lst):
count = 0
test = []
for line in lst:
test += line.split()
for i in lst:
count = count +1
if count % 2 == 0:
x = count//2
y = lst[x]
z = lst[x-1]
median = (y + z)/2
return median
if count %2 == 1:
x = (count-1)//2
return lst[x] # Where the problem persists
def main():
lst = open(input("Input file name: "), "r")
print(medianStrat(lst))
Run Code Online (Sandbox Code Playgroud)
那么问题的解决方案是什么,或者可以做些什么来使代码工作呢?(代码应该执行的主要功能是打开文件并获取中位数)
你不能索引(__getitem__)一个 _io.TextIOWrapper对象.你能做的就是使用一条list线.在您的代码中尝试此操作:
lst = open(input("Input file name: "), "r").readlines()
Run Code Online (Sandbox Code Playgroud)
此外,您没有关闭file对象,这会更好:
with open(input("Input file name: ", "r") as lst:
print(medianStrat(lst.readlines()))
Run Code Online (Sandbox Code Playgroud)
with确保文件关闭,请参阅文档