Better writing in python

Harold Fellermann dadapapa at googlemail.com
Wed Oct 24 15:14:28 CEST 2007


Hi Alexandre,

On Oct 24, 2:09 pm, Alexandre Badez <alexandre.ba... at gmail.com> wrote:
> I'm just wondering, if I could write a in a "better" way this code

Please tell us, what it is you want to achieve. And give us some
context
for this function.

> lMandatory = []
> lOptional = []
> for arg in cls.dArguments:
>   if arg is True:
>     lMandatory.append(arg)
>   else:
>     lOptional.append(arg)
> return (lMandatory, lOptional)

This snippet will seperate d.Arguments into two lists: one that
holds all elements that are references to True(!) and another list
that holds the rest. The condition 'if args is True' will only
be hold if arg actually _is_ the object _True_. This is probably
not what you want. Apart from that, you might go with

lMandatory = [ arg for arg in cls.dArguments if condition() ]
lOptional = [ arg for arg in cls.dArguments if not condition() ]

the second line could be rewritten

lOptional = list(set(cls.dArguments)-set(lMandatory))

If lMandatory and lOptional do not need to be lists, you can also
write

lMandatory = set(arg for arg in cls.dArguments if condition())
lOptional =  set(cls.dArguments) - lMandatory

But please, give us some more context of what you want to do.

- harold -




More information about the Python-list mailing list