如标题所示获取错误。 这是追溯。我知道lst [x]导致了这个问题,但不太确定如何解决这个问题。我已经搜索了google + 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
这是实际代码
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))
那么这个问题的解决方案是什么,或者可以做些什么来使代码工作呢? (代码应该执行的主要功能是打开文件并获取中位数)
答案 0 :(得分:7)
您无法索引(__getitem__
)_io.TextIOWrapper
个对象。你可以做的是使用list
行。在您的代码中尝试此操作:
lst = open(input("Input file name: "), "r").readlines()
此外,您还没有关闭file
对象,这会更好:
with open(input("Input file name: ", "r") as lst:
print(medianStrat(lst.readlines()))
with
确保文件已关闭,请参阅docs