Better writing in python
Marc 'BlackJack' Rintsch
bj_666 at gmx.net
Wed Oct 24 11:51:44 EDT 2007
On Wed, 24 Oct 2007 16:04:28 +0200, A.T.Hofkamp wrote:
>> On 2007-10-24, Alexandre Badez <alexandre.badez at gmail.com> wrote:
>> I'm just wondering, if I could write a in a "better" way this
>> code
>>
>> lMandatory = []
>> lOptional = []
>> for arg in cls.dArguments:
>> if arg is True:
>> lMandatory.append(arg)
>> else:
>> lOptional.append(arg)
>> return (lMandatory, lOptional)
>>
>> I think there is a better way, but I can't see how...
>
> You can do it shorter, not sure that it also qualifies as better....
>
> d = { True : [] , False : [] }
> for arg in cls.arguments:
> d[arg == True].append(arg)
>
> return d[True], d[False]
>
> One potential problem here is that 'arg == True' may not be the same as 'if
> arg:'. I couldn't come up with a better equivalent expression, maybe one of the
> other readers knows more about this?
With ``if arg:`` the interpreter asks `arg` for its "boolean value". So a
better way would be:
d[bool(arg)].append(arg)
As `True` and `False` are instances of `int` with the values 1 and 0 it's
possible to replace the dictionary by a list:
tmp = [[], []]
for arg in cls.arguments:
tmp[bool(arg)].append(arg)
return tmp[1], tmp[0]
Maybe that's nicer. Maybe not.
Ciao,
Marc 'BlackJack' Rintsch
More information about the Python-list
mailing list