[Tutor] selecting elements from a list that do not meet selection criteria
Ricardo Aráoz
ricaraoz at gmail.com
Fri Nov 16 14:16:47 CET 2007
ted b wrote:
> Is there a way i can select all elements from a list
> that do not meet selection criteria. I want to be able
> to select elements that have values of, say, < 1 but
> only if at least one of the elements has a value of >
> 0.
>
> What i mean is, for example, in the code below, if one
> of the elements of "list 'a'" has a value greater than
> 1, then i want to print all the other elements in the
> list (i.e., class One and class Three) and to do
> otherStuff associated with those classes. Right now,
> it prints those elements that *do* have values of > 0,
> (i.e. class Two). But in situations where all of the
> classes have values set to 0, then i don't want
> anything selected.
>
> I don't want to just use something like "if x.value()
> != 0" or "if x.value() < 1" since those would give
> results if all elements were less than 1, and i only
> want to select elements of the list that are less than
> 1 if at least one of the elements is > 1.
>
> Here's the sample code:
>
> class One:
> def value(self):
> return 0
>
> class Two:
> def value(self):
> return 1
>
> class Three:
> def value(self):
> return 0
>
> a = [One(), Two(), Three()]
>
> for x in a:
> if x.value() > 0:
> print x
> x.otherStuff()
>
> Thanks in advance!!! :)))
>
>>> doit = [1,2,0,-1,-3,-5,-7]
>>> dont = [0,-1,-3,-5,-7,-9,-11]
>>> [i for i in dont if max(dont) > 0 and i < 1]
[]
>>> [i for i in doit if max(doit) > 0 and i < 1]
[0, -1, -3, -5, -7]
HTH
More information about the Tutor
mailing list