Is there a function in python that returns true if all members of an iterable are true?

StackOverflow https://stackoverflow.com/questions/18690162

  •  28-06-2022
  •  | 
  •  

سؤال

I'm tryng to learn different ways to do simple things in python, while also learning a bit about some functional practices. I have some numbers that the user inputs, and I want to know if they really are numbers. I've come up with this kind of classic solution:

def foo(list_of_inputs):
    for n in list_of_inputs:
       if not hasattr(n, "real"):
           # some number is not a number!
           return False
    # all are numbers
    return True

But then, I figured out this other "thing" that may have some potential:

def foo(list_of_inputs):
    bool_list = map(lambda input: hasattr(input, "real"), list_of_inputs)
    return reduce(lambda x, y: x == y, bool_list)

I think that maybe a function that returns "True" if all members of a collection, iterable, or whatever the correct concept I'm looking for, are "True", may already be something somewhat common, and also, this second attempt doesn't return when a "False" is found, while the classic one does... But I find it elegant, and maybe that is because I'm not there yet with programming in general.

So my question is: what's the "probably better" way to do this?

هل كانت مفيدة؟

المحلول

As mentioned, the all function will do what you want. What you describe you're trying to do can also be done with the str.isnumeric() function.

def foo(listOfInputs):
    return all(map(str.isnumeric,listOfInputs))

Edit: I'm finding that it fails on ['1','2','3.14','4'] which is a little annoying. Maybe someone can come up with a cleverer solution than this, but I decided to wrap a slightly modified approach in a try:

def foo(listOfInputs):
    try:
        return all(map(float,listOfInputs))
    except ValueError:
        return False

That works on:

['1','2','-3','4']
['1','2','3.14','4']

نصائح أخرى

You mean something like the built-in all function?

Return True if all elements of the iterable are true (or if the iterable is empty). Equivalent to:

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top