[Tutor] Lists on the fly?
Luke Paireepinart
rabidpoobear at gmail.com
Sat Dec 23 11:33:22 CET 2006
[snip]
> # Get Levels List
> for Element in Elements:
> Lev_List['Level_%i' % (Element['Level'])] = []
>
> # Append Element to corresponding Level
> for Element in Elements:
> Lev_List['Level_%i' % (Element['Level'])].append(Element['Name'])
[snip snip]
> Probably the first loop is a little redundant, but performance is not
> one of my concerns now, but in the future the project will not be
> composed by a handful of spaces, probably by hundreds or more.
>
I think a better way to do this is to check if 'Level_%i' is in your
dictionary already.
so the loop becomes
Lev_List = {}
for Element in Elements:
keystr = 'Level_%i' % Element['Level']
if not Lev_List.has_key(keystr):
Lev_List[keystr] = []
Lev_List[keystr].append(Element['Name'])
And of course you can go the EAFP (easier to ask forgiveness than
permission)
route and use a try/accept block
Lev_List = {}
for Element in Elements:
keystr = 'Level_%i' % Element['Level']
try:
Lev_List[keystr].append(Element['Name'])
except KeyError:
Lev_List[keystr] = [Element['Name']]
I suspect the try/accept would be the fastest,
but you'd have to timeit to be sure, of course.
HTH,
-Luke
More information about the Tutor
mailing list