首页 > 解决方案 > 如何仅检索 args 列表中的非负值(理解)?

问题描述

#我应该如何消除那些像“4”和“5”这样的字符串元素?#

理想的输出或结果应如下所示:

>>> 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]

我的代码:

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

我的输出:

>>> 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']

如何解决这个问题?</p>

标签: pythonpython-3.x

解决方案


您只需要检查每个参数的类型:

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]

请注意,我已将参数的名称更改为更准确,如我的评论中所述。


推荐阅读