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

Chris Roy-Smith chris_roysmith at internode.on.net
Mon May 9 23:27:14 EDT 2016


On 10/05/16 12:01, Steven D'Aprano wrote:
> 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)
Thank you,
that's much better
I thought I needed the extra columns, but I changed things to use 2 
lists of lists
(one generated with the above line and another to hold my calculated 
results)

>
> 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)])
>
>
>



More information about the Tutor mailing list