【问题标题】:Average, per day. Python平均,每天。 Python
【发布时间】:2021-05-21 08:58:46
【问题描述】:

所以,我有这个file.txt,还要做每天的平均气温,file.txt要大很多,所以有很多天

data : 2021-05-01 16:52:13.074093
Temperature: 25.20 C
Pressure:    986.57 hPa 
Altitude:    224.50 
data : 2021-05-01 16:52:18.129364
Temperature: 25.20 C
Pressure:    986.55 hPa 
Altitude:    224.61 

我做了平均,但我不知道每天如何做 这是到目前为止的代码

def temperature():
    print("The average temperature is:")
    total = 0.0
    c = 0
    with open("text.txt", 'r') as f:
        for line in f:
            if "Temperature" not in line: continue
            temp = line.split(" ")[1]
            total =total+ float(temp)
            c =c+ 1
    print(total / c)

【问题讨论】:

    标签: python python-3.x average


    【解决方案1】:
    def temperature():
        print("The average temperature is:")
        total = 0.0
        c = 0
        alltemp=[]
        with open(r"C:\VM\remove it.txt", 'r') as f:
            for line in f:
                if "Temperature" not in line: continue
                temp = line.split(" ")[1]
                total =total+ float(temp)
                c =c+ 1
                alltemp.append(total / c)
        print(total / c)
        return alltemp
    

    alltemp 将为您提供列表中的所有温度

    【讨论】:

      【解决方案2】:

      这是一种在纯 Python 中实现的方法:

      def temperature():
          temperatures = {}
          with open("text.txt", 'r') as f:
              for line in f:
                  if "data" in line:
                      day = line.split(" ")[2].strip()
                  if "Temperature" in line:
                      temp = float(line.split(" ")[1])
                      if day in temperatures:
                          temperatures[day].append(temp)
                      else:
                          temperatures[day] = [temp]
      
          for key,value in temperatures.items():
              print("Mean temperature on {} was {}".format(key, sum(value)/len(value)))
      

      想法:假设日期总是先于温度,我们可以按顺序进行,先读取日期,然后读取温度。

      当您遇到“数据”(日期?)行时,拆分(或正则表达式)以仅保留日期,并将其用作填写字典的键。这些值是当天的温度列表。完成后,每天遍历您的字典,并计算平均值(当天温度列表的总和除以长度)。

      我的回答中有一些硬编码的值。您的文件有点“损坏”(日期行称为“数据”?行之间的冒号不一致,data : temperature: ),因此请确保split 中的位置正确。如果您不能保证整个文件的一致性,请使用正则表达式。

      【讨论】:

        【解决方案3】:

        由于日期和温度位于不同的行上,因此您的代码需要记住当前(最后一次出现)日期。然后您可以对每天的温度进行分组,例如在字典中:

        from collections import defaultdict
        
        temp_per_day = defaultdict(list)
        current_day = None
        total = count = 0
        
        for line in f:
            if line[:4] == 'data':
                current_day = line.split()[2]
            elif 'Temperature' in line:
                temp = float(line.split()[1])
                total += temp
                count += 1
                temp_per_day[current_day].append(temp)
        

        然后您可以迭代每天的温度值并计算平均值:

        for day, temps in temp_per_day.items():
            avg_temp = sum(temps) / len(temps)
            print(f'average temperature on {day} is {avg_temp:.2f}')
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-03-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多