[Tutor] detecting a change in a iterable object (list, array, etc.)
Tim Michelsen
timmichelsen at gmx-topmail.de
Tue Dec 18 17:44:57 CET 2007
Hello,
> A list comprehension will work for this. If data is a list of triples of
> (year, month, volume) then this will give you a list of the 1997 triples:
>
> data1997 = [ item for item in data if item[0]==1997 ]
I tried your code out (see below).
Here is the output:
[]
[]
[]
[]
[]
[1990, 0, 1, -18.0]
[1990, 0, 2, -0.5]
[1990, 0, 3, -14.0]
[1990, 0, 4, -21.0]
How do I avoid the []?
What whould be the easiest way to save this list (without the "[]") into a file
and append a newline after each row?
Thanks for your help in advance,
Timmie
Here's the code:
#!/usr/bin/env python
# currently used modules
import csv
# SOME VARIABLES
#~ stattion_name = 'Sosan'
input_file_name = '../data/filter_test_data.csv'
output_file_name = '../data/filter_test_data_result.csv'
# prepare files
input_file = open(input_file_name, 'r')
output_file = open(output_file_name ,'w')
header = u"Year, Month, Day, Hour_of_day [h], values, \n"
input_data = csv.reader(input_file, delimiter=';')
#~ skip the first rows
line1 = input_file.readline()
line2 = input_file.readline()
#~ write the header
output_file.write(header.encode('utf-8'))
counter = 0
value_col = 6
for line in input_data:
#~ print line
#~ year month day temp_3hr
year = int(line[1])
month = int(line[2])-1
day = int(line[3])
value = float(line[6])*0.5
compact_list = [year, month, day, value]
res_rows = [ item for item in compact_list if compact_list[0] == 1990 ]
print res_rows
input_file.close()
output_file.close()
More information about the Tutor
mailing list