gpt4 book ai didi

python - 列表索引超出范围(使用 while 循环)

转载 作者:行者123 更新时间:2023-12-01 08:21:18 26 4
gpt4 key购买 nike

我正在为 edx 类(class)做作业,当它运行 while 循环时,我的代码中出现“索引超出范围”错误,即使它最终给出了正确的输出。

这是我的代码:

# [] create The Weather
# [] copy and paste in edX assignment page
!curl https://raw.githubusercontent.com/MicrosoftLearning/intropython/master/world_temp_mean.csv -o mean_temp.txt

mean_temp = open('mean_temp.txt', 'a+')
mean_temp.write("Rio de Janeiro,Brazil,30.0,18.0\n")

mean_temp.seek(0)

headings = mean_temp.readline().split(',')

city_temp = mean_temp.readline().split(',')
while city_temp:
print(headings[0].capitalize(), "of", city_temp[0], headings[2], "is", city_temp[2], "Celsius")
city_temp = mean_temp.readline().split(',')

mean_temp.close()

最佳答案

我已经对此进行了测试,它应该可以工作。我认为你的 while 子句没有正确找到文件的末尾 - for 循环可以工作并且更干净。

with open("mean_temp.txt", "a") as f:
f.write("\nRio de Janeiro,Brazil,30.0,18.0")

with open("mean_temp.txt", "r") as f:
headings = f.readline().split(',')
for next_line in f:
next_line = next_line.split(',')
print(headings[0].capitalize(), "of", next_line[0], headings[2], "is", next_line[2], "Celsius")

关于python - 列表索引超出范围(使用 while 循环),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54634169/

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