Domanda

Both code examples below are old examples of a problem I have where I am iterating through a list of numbers to find numbers that fit a list of conditions but couldn't find a neat way to express it except for:

condition1 and condition2 and condition3 and condition4 and condition5

Two examples of the above:

if str(x).count("2")==0 and str(x).count("4")==0 and str(x).count("6")==0 and str(x).count("8")==0 and str(x).count("0")==0:

if x % 11==0 and x % 12 ==0 and x % 13 ==0 and x%14==0 and x %15 == 0 and x%16==0 and x%17==0 and x%18==0 and x%19==0 and x%20==0:

Is there a simple, more neat way of doing this?

My first retry was to store the conditions in a list like below:

list=["2","4","6","8","0"]
for element in list:
    #call the function on all elements of the list
list=[11,12,13,14,15,16,17,18,19,20]
for element in list:
    #call the function on all elements of the list

but I was hoping for an even neater/simpler way.

È stato utile?

Soluzione

You can use a generator expression like this

def f(n):
    return x%n

if all(f(element) for element in lst):
    ...

If the function/calculation is not too complex, you can just put it inline

if all(x % element for element in lst):
    ...

Altri suggerimenti

The built in function all can simplify this, if you can express your conditions in a generator expression:

result = all(x % n == 0 for n in xrange(11, 21))

It returns a boolean result indicating whether or not all the elements of its iterable argument are True, short-circuiting to end evaluation as soon as one is False.

This is the second question I've seen in the last hour or so for which all is the answer - must be something in the air.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top