Biu
Biu

Reputation: 21

If condition in Python and create list

I just started to learn python. I have a csv file contains three row: date, time and temperature. Now I want to screen all temperature data > 80 and then put the screened lines into a list and print them.

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)

Could you help me to fix it? Thanks.

Upvotes: 0

Views: 268

Answers (1)

Barmar
Barmar

Reputation: 781004

Make an array of dictionaries, not 3 separate arrays.

The second loop should iterate over the array that you filled in, not csv_reader. There's nothing left to process in csv_reader, because the previous loop reached the end of it.

You should also convert the temperature to a number.

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)

Upvotes: 1

Related Questions