[Tutor] selecting elements from a list that do not meet selection criteria
Kent Johnson
kent37 at tds.net
Thu Nov 15 13:31:40 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.
I'm not sure if you mean > 0 or >1, you seem to say both at different times.
> 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.
Use any():
if any(x.value() > 0 for x in a):
for x in a:
if x.value() > 0:
print x
x.otherStuff()
> Here's the sample code:
>
> class One:
> def value(self):
> return 0
BTW this style of programming - using getter methods to access values -
is not idiomatic Python. Better would be to use a value attribute directly:
class One:
def __init__(self):
self.value = 0
Then refer to One().value instead of One().value()
Kent
More information about the Tutor
mailing list