PDA

View Full Version : [SOLVED] Python needs simplification/optimization



J V
January 12th, 2010, 03:57 PM
My problem is that this might go on forever, I need something that can simply say str, str, str as many times as count...


if(count == 4):
model = gtk.ListStore(str,str,str,str)
elif(count == 3):
model = gtk.ListStore(str,str,str)
elif(count == 2):
model = gtk.ListStore(str,str)
else:
model = gtk.ListStore(str)

delfick
January 12th, 2010, 04:25 PM
model = gtk.ListStore(*(str for _ in range(count)))


:D

(should probably also have checks to make sure count is greater than zero)

basically it creates a tuple of many str to the length of count and then using magic * to pass them in as positional arguements....

diesch
January 12th, 2010, 04:38 PM
A little bit shorter:


model = gtk.ListStore(*(str,)*count)

J V
January 12th, 2010, 05:21 PM
thanks bot of you for the help, I'll never understand python tuples/lists/etc :)

nvteighen
January 12th, 2010, 06:01 PM
thanks bot of you for the help, I'll never understand python tuples/lists/etc :)

The only thing to understand is that argument lists are tuples (i.e. immutable lists) and that there's a unary * operator which sorta "remove the parens" from a tuple and allows you to include it inside another tuple.

FYI, this * operator is based on Lisp's "comma-splicing".

J V
January 12th, 2010, 07:22 PM
right, well thanks for that! (never done lisp)