我目前正在学习python,我在练习的某些部分遇到困难:
使用!curl将https://raw.githubusercontent.com/MicrosoftLearning/intropython/master/world_temp_mean.csv下载为mean_temp.txt
#[]天气:将world_mean_team.csv导入为mean_temp.txt 以“ r”模式打开文件。 将文本的第一行读取到一个名为heading和print()
的变量中。 使用.split(',')
将标题转换为列表,该列表在每个逗号print()
列表上分开。
#[]天气:打开文件,读/打印第一行,将行转换为列表(以逗号分隔) 使用while循环从文件中读取剩余的行 将剩余的行分配给city_temp
变量。 对于循环中的每个city_temp
,使用.split(',')
将.readline()
转换为列表。 打印每个城市和最高的月平均温度。 关闭mean_temps
。提示和提示:
使用标题的打印输出来确定要使用的
city_temp
索引。 北京的“月平均值:最高”是30.9摄氏度。 使用city_temp
将.split(',')
转换为列表。
#[]天气:使用while循环可打印城市和摄氏最高的每月平均温度
我正确地完成了第一部分,但是第二部分却很难打印每个城市的温度,而且我不知道该如何解决。
到目前为止,我的代码是:
mean_temp = open('mean_temp.txt', 'r')
read_line = mean_temp.readline()
print(read_line)
heading = read_line.split(',')
print('Heading list: ',heading)
city_temp = ''
while read_line:
print(read_line[:-1]) # writes the first line in the file
read_line = mean_temp.readline() # goes to the next line
city_temp += read_line # adding the line to the variable
city_temp1 = city_temp.split(',') # split the line every comma to a list
print(city_temp1)
,输出为:
city,country,month ave: highest high,month ave: lowest low
Heading list: ['city', 'country', 'month ave: highest high', 'month ave: lowest low\n']
city,country,month ave: highest high,month ave: lowest low
Beijing,China,30.9,-8.4
Cairo,Egypt,34.7,1.2
London,UK,23.5,2.1
Nairobi,Kenya,26.3,10.5
New York City,USA,28.9,-2.8
Sydney,Australia,26.5,8.7
Tokyo,Japan,30.8,0.9
['Beijing', 'China', '30.9', '-8.4\nCairo', 'Egypt', '34.7', '1.2\nLondon', 'UK', '23.5', '2.1\nNairobi', 'Kenya', '26.3', '10.5\nNew York City', 'USA', '28.9', '-2.8\nSydney', 'Australia', '26.5', '8.7\nTokyo', 'Japan', '30.8', '0.9\n']
答案 0 :(得分:0)
您的while循环应将行拆分为一个列表,然后使用正确的整数对该列表进行索引以提取城市和高温信息。例如:
mean_temp = open('mean_temp.txt', 'r')
read_line = mean_temp.readline()
heading = read_line.split(',')
print('Heading list: ',heading)
# prints "Heading list: ['city', 'country', 'month ave: highest high', 'month ave: lowest low\n']",
# which means index ZERO and index TWO is the correct values to pull from each list created from each line
# Move onto the next line, we want to start the while loop with the first city
city_temp = mean_temp.readline() # goes to the next line
while city_temp:
# print(read_line[:-1]) # don't write the whole line to the console, we want to print just the CITY and HIGH TEMP
city_info = city_temp.split(',') # This is the list
print(city_info[0] + ': ' + city_info[2])
city_temp = mean_temp.readline() # go to the next line at the end of the while loop
# make sure to close the file like the instructions said
mean_temp.close()
以上代码的输出为:
Heading list: ['city', 'country', 'month ave: highest high', 'month ave: lowest low\n']
Beijing: 30.9
Cairo: 34.7
London: 23.5
Nairobi: 26.3
New York City: 28.9
Sydney: 26.5
Tokyo: 30.8