[Tutor] A list in list problem
János Juhász
janos.juhasz at VELUX.com
Mon Aug 21 14:58:50 CEST 2006
Hi Dave,
> From: dave s <pythontut at pusspaws.net>
> Subject: [Tutor] A list in list problem
> To: python tutor <tutor at python.org>
> Message-ID: <200608210959.01834.pythontut at pusspaws.net>
> Content-Type: text/plain; charset="us-ascii"
> def CSV_Lines(self, csv, from_, to):
> """Returns a list of cleaned up lines from csv 'from_' line
> number 'to' line number"""
> clean_line = clean_csv = []
> for string in range(from_, to):
> split_string = csv[string].split(',')
> split_string = split_string[1:-1] # Strip the LHS column
+ the /n'
> if split_string[0] == '' : continue # Skip empty lines
> print '##########################'
> print 'split_string ', split_string
> for string in split_string:
> if len(string) > 0:
clean_line.append(string[1:-1])
> print 'clean_line ',clean_line
> clean_csv.append(clean_line)
> print 'clean_csv ',clean_csv
> clean_line = []
>
> But I get clean_csv trouble ...
> ubuntu at ubuntu:~/python_develop/unison/PxQxAudit/main$ ./crosscheck.py
> ##########################
> split_string ['"temp1"', '"wow a variable"', '', '', '']
> clean_line ['temp1', 'wow a variable']
> clean_csv ['temp1', 'wow a variable', [...]]
> ##########################
> split_string ['"temp2"', '', '', '', '']
> clean_line ['temp2']
> clean_csv ['temp1', 'wow a variable', [...], ['temp2']]
> ubuntu at ubuntu:~/python_develop/unison/PxQxAudit/main$
> ie clean_csv ends up as ['temp1', 'wow a variable', [...], ['temp2']]
instead
> of [[temp1, wow a variable], [temp2]]
You have used string as variable name two times, once as an integer and
once as a field in the line.
It should be avoided.
I like list comprehension in this case.
def CSV_Lines2(csv, from_, to):
csv = csv[from_ : to] # We are
interested just here
csv = [line.split(',') for line in csv] # Make a 2D array from the
list
return [LineItems[1:-1] for LineItems in csv if len(LineItems) > 2]
# filter out first and last columns, and lines with
too less items
csv = """Header1
Header2
temp1,12,20,1
temp2,22,22,2
temp3,33,44,3
temp4,34,64,4
Footer1
Footer2"""
csv = csv.split('\n')
print CSV_Lines2(csv, 2, 6)
>>>[['12', '20'], ['22', '22'], ['33', '44'], ['34', '64']]
Yours sincerely,
______________________________
Janos Juhasz
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060821/bf941136/attachment.htm
More information about the Tutor
mailing list