gpt4 book ai didi

python - 类型错误: '_io.TextIOWrapper' 对象不可订阅

转载 作者:太空狗 更新时间:2023-10-29 21:00:51 24 4
gpt4 key购买 nike

代码应该做的主要功能是打开文件并获取中位数。这是我的代码:

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))

这是我得到的错误:

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

我知道 lst[x] 导致了这个问题,但不太确定如何解决这个问题。那么这个问题的解决方案是什么,或者可以做些什么来使代码正常工作?

最佳答案

您不能索引 ( __getitem__ ) _io.TextIOWrapper目的。你可以做的是使用 a list of lines .在您的代码中试试这个:

lst = open(input("Input file name: "), "r").readlines()

此外,您没有关闭 file 对象,这样会更好:

with open(input("Input file name: ", "r") as lst:
print(medianStrat(lst.readlines()))

with确保文件被关闭。

关于python - 类型错误: '_io.TextIOWrapper' 对象不可订阅,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28977477/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com