[Tutor] is there a better way to do this?

Steven D'Aprano steve at pearwood.info
Mon May 9 22:01:58 EDT 2016


On Mon, May 09, 2016 at 06:13:32PM +1000, Chris Roy-Smith wrote:

> data = [[" " for x in range(9)] for y in range(count)]
> for (ddate, mood, walk, lag, sleep) in curs:
>         data[row][0]=ddate
>         data[row][1]=mood
>         data[row][2]=walk
>         data[row][3]=lag
>         data[row][4]=sleep
>         row +=1
> 
> While I don't know a better way to do this, it seems a bit awkward, is 
> there a better way?

Hmmm, it's hard to be sure because we don't really know what count is. 
Do you want a bunch of empty rows at the end? My guess is No. 

In your code above, you initialise each row with ten spaces, and only 
replace five of them. So assuming you need the extra five spaces:

data = [record + [" "]*5 for record in curs]

provided curs returns lists, rather than tuples. (If not, it's 
easy to just convert using `list(record)`.

If you don't need the extra five columns, the code is even simpler:

data = list(curs)


What if you do want extra blank rows? Easiest to just add them at the 
end:

# initialise data as above, then add blanks
for i in range(how_many_extra_rows):
    data.append([" "]*10)

which can be simplified to:

data.extend([[" "]*10 for i in range(how_many_extra_rows)])



-- 
Steve


More information about the Tutor mailing list