Python脚本必须与温度一起工作

2024-06-23 19:19:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我要做一个脚本,需要一个txt文件巫婆包含所有的月份名称和每天的温度,并导出一个文件,每个月的最热温度和全年最冷的温度 我困在这个代码块,我不能得到它来工作我的方式,所以我需要帮助之前,我拆除我的电脑。。。:)建议中的thanx!你知道吗

integers = open('temperatures.txt', 'r')

largestInt = 0 
smallestInt = 0

for line in integers:
    integers = line.split (' ')
    if largestInt <= int(line.strip()): 
        largestInt = int(line.strip()) 
    if smallestInt >= int(line.strip()): 
        smallestInt = int(line.strip()) 

integers.close()


print ("Smallest = ", smallestInt)
print ("Largest = ", largestInt)

january -16 -12 -15 -20 0 -1 -20 -2 -20 -14 -18 -8 2 -1 -14 -7 -15 -17 -6 -17 -17 -7 0 3 -20 -17 -15 -8 -12 3
february -9 -2 -7 1 -16 -19 -19 -11 -16 -15 -9 -2 -16 -4 -20 -5 -6 -17 -5 0 -16 2 0 -20 -16 -2 -18
march 2 -9 -1 -3 -6 -2 1 -2 -3 -9 -1 -4 0 -6 -7 1 0 2 -5 -10 2 -7 -3 2 -10 2 -9 -8 -5 -2
april -5 0 10 -9 0 -9 -8 6 -5 3 -1 4 9 -1 2 0 10 0 5 0 -10 0 6 3 -6 -2 -10 -8 -2
may 12 5 8 -1 -2 4 10 -1 7 15 7 3 6 4 10 9 13 6 14 10 14 2 6 12 15 2 14 11 9 1
june 12 5 17 6 10 14 9 7 15 23 29 11 16 18 9 25 14 8 16 22 19 22 23 18 16 16 26 24 22
july 15 8 21 28 18 13 9 9 8 6 8 12 12 29 28 20 6 9 12 8 14 18 14 13 23 6 24 24 17 20
august 7 6 5 19 18 18 17 20 15 11 7 10 13 12 20 11 10 14 18 14 24 6 17 16 6 17 5 13 11
september 21 19 21 9 13 18 6 6 20 7 25 13 8 9 14 16 19 10 7 25 7 17 16 15 17 18 15 9 19
october 2 2 1 5 -2 5 5 2 2 2 1 -2 1 -2 0 -2 5 4 0 1 -1 2 0 2 2 2 -1 1 4 -1
november -6 -7 -2 -7 -2 -4 0 -7 -8 -6 0 -9 -2 -3 -2 0 -8 -2 -5 -2 -5 -8 -10 0 -2 -9 -9 -7 -1
december -15 2 -11 -14 -15 -5 -5 -18 -18 -19 0 0 2 -7 -16 -7 -4 -1 -1 -16 -18 -10 -3 -19 -6 -16 -16 -8 -2 -18

Tags: 文件integers代码txt脚本名称ifline
1条回答
网友
1楼 · 发布于 2024-06-23 19:19:35

你的代码中有许多错误。您提到您想要每个月的最热/最冷温度,但是您的代码的目的似乎是在所有行(因此全年)中查找最小/最大温度。你知道吗

我建议使用带有open函数的with语句,它会自动为您关闭文件。你知道吗

integers = line.split (' ')将返回字符串列表。但是要注意每行末尾的\n字符。而且列表的第一个元素是月份,所以需要将其与数字分开。你知道吗

if largestInt <= int(line.strip())是错误的。line是作为字符串的整行,strip()只是删除字符串开头和结尾的空白。如果要进行此比较,请对整数列表使用max()函数。或者遍历列表并比较每个元素。在进行这样的比较之前,请确保将从split()函数返回的列表中的数字实际转换为整数。你知道吗

不管你的目标是什么。剩下的我会让你想清楚的。你知道吗

with open('temperatures.txt', 'r') as integers:
    for line in integers:
        data = line.rstrip().split(' ')
        month, integers = data[0], [int(x) for x in data[1:]]
        print(month, min(integers), max(integers))

相关问题 更多 >

    热门问题