Re: do this with list comp?
From: Diez B. Roggisch (deets_noospaam_at_web.de)
Date: 12/13/03
- Next message: Diez B. Roggisch: "Re: Quickcam and various platforms"
- Previous message: tudor: "Re: python2.3 upgrade"
- In reply to: John Hunter: "do this with list comp?"
- Next in thread: Dang Griffith: "Re: do this with list comp?"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Sat, 13 Dec 2003 15:46:15 +0100
John Hunter wrote:
>
> I want to replace all empty fields in a CSV line with 'NULL'.
>
> Here is a brute force way
>
> def fixline(line):
> ret = []
> for s in line.split(','):
> if not len(s): ret.append('NULL')
> else: ret.append(s)
> return ret
>
> line = 'John,Bill,,,Fred'
> print fixline(line)
> # ['John', 'Bill', 'NULL', 'NULL', 'Fred']
>
> I am wondering if there is a way to do it with list comprehensions. I
> know how I would do it with a ternary operator.....
This should work:
res = [[s, 'NULL'][not len(s)] for s in line.split(",")]
Diez
- Next message: Diez B. Roggisch: "Re: Quickcam and various platforms"
- Previous message: tudor: "Re: python2.3 upgrade"
- In reply to: John Hunter: "do this with list comp?"
- Next in thread: Dang Griffith: "Re: do this with list comp?"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|