python - 如果 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)
你能帮我修一下吗?谢谢。
解决方案
制作一个字典数组,而不是 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)
推荐阅读
- python-3.x - 我可以用什么来测量 3D (x,y,z) 中的某些属性?Regionprops 文档说它仅适用于 (N, M) 但我找到了 3D regionprops PR 的信息
- java - 如何在 Firebase Vision 文本识别器中设置字符白名单
- php - Symfony 控制台:对服务感到困惑
- xml - 在组件中将 XML 结果显示为数组
- mysql - mysql查询使用分区名称与where子句
- javascript - 如何仅使用 javascript 创建带有左/右幻灯片动画的图像幻灯片?
- linux - Curl bash脚本被截断/合并
- loops - 将 Ansible 异步与重试相结合
- python-3.x - Pandas groupby TypeError:'SeriesGroupBy'和'int'的实例之间不支持'>'
- amazon-web-services - 关闭 AWS CloudTrail 的审计跟踪