Home > Mobile >  How to retrieve only non-negative values in a args list(comprehension)?
How to retrieve only non-negative values in a args list(comprehension)?

Time:11-02

#How should I eliminate those string elements like "4" and "5"? #

The ideal output or results should be like below:

>>> filter_positives_from_args(-3, -2, -1, 0, 1, 2, 3)
    [0, 1, 2, 3]
>>> filter_positives_from_args(-3, -2, -1, 0, 1, 2, 3, '4', '5')
    [0, 1, 2, 3]
>>> filter_positives_from_args(-3, -2, -1, False, True, 2, 3, '4', '5')
    [False, True, 2, 3]

My code:

def filter_positives_from_args(*args) -> list:
ans = [p for p in args if int(p) >= 0]
return(list(filter(None,ans)))

My output:

>>> print(filter_positives_from_args(-3, -2, -1, 0, 1, 2, 3))
[1, 2, 3]
>>> print(filter_positives_from_args(-3, -2, -1, 0, 1, 2, 3, '4', '5'))
[1, 2, 3, '4', '5']
>>> print(filter_positives_from_args(-3, -2, -1, False, True, 2, 3, '4', '5'))
[True, 2, 3, '4', '5']

How to solve this problem?

CodePudding user response:

You just need to also check the type of each argument:

def filter_non_negatives(*args):
    valid_types = {bool, int, float, complex}
    return [p for p in args if type(p) in valid_types and p >= 0]

Note that I've changed the name of the argument to be more accurate, as explained in my comment.

CodePudding user response:

Another approach just using try catch mechanism:

def filter_positives_from_args(*data):
    out = []
    for d in data:
        try:
            if d >= 0:
                out.append(d)
        except Exception as ex:
            pass
    return out
print (filter_positives_from_args(-3, -2, -1, False, True, 2, 3, '4', '5'))
print (filter_positives_from_args(-3, -2, -1, 0, 1, 2, 3, '4', '5'))

Output:

[False, True, 2, 3]
[0, 1, 2, 3]
  • Related