首页 > 解决方案 > 如果 Python 中的条件并创建列表

问题描述

我刚开始学习python。我有一个 csv 文件包含三行:日期、时间和温度。现在我想筛选所有> 80的温度数据,然后将筛选的行放入列表中并打印出来。

import csv
date_array = []
time_array = []
temp_array = []
output = []

with open("/Users/Fay/Documents/GitHub/warning_system/temp.csv") as csvfile:
    csv_reader = csv.reader(csvfile, delimiter=",")
    next(csv_reader, None)
    for row in csv_reader:
        date_array.append(row[0])
        time_array.append(row[1])
        temp_array.append(row[2])
        #why to disassemble the data vertically instead of horizontally, line by line. 
    #print(data_array[1])
    #print(time_array[1])
    #print(temp_array[1])


    for row in csv_reader:
        output= ['data_array','time_array','temp_array']
       if temp_array > '80':
    print(output)

你能帮我修一下吗?谢谢。

标签: python

解决方案


制作一个字典数组,而不是 3 个单独的数组。

第二个循环应该遍历您填写的数组,而不是csv_reader. 中没有任何东西需要处理csv_reader,因为前一个循环到达了它的末尾。

您还应该将温度转换为数字。

import csv
data_array = []
output = []

with open("/Users/Fay/Documents/GitHub/warning_system/temp.csv") as csvfile:
    csv_reader = csv.reader(csvfile, delimiter=",")
    next(csv_reader, None)
    for row in csv_reader:
        data_array.append({"date": row[0], "time": row[1], "temp": float(row[2])})

for item in data_array:
    if item['temp'] > 80:
        output.append(item)

print(output)

推荐阅读