python - 如何仅检索 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>
解决方案
您只需要检查每个参数的类型:
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]
请注意,我已将参数的名称更改为更准确,如我的评论中所述。
推荐阅读
- ruby - 用于 ip 地址的电子邮件发件人分数的 Api
- javascript - React useEffect 停止无限循环
- azure - 当依赖的任务完成但在 Azure 批处理中失败时,有没有办法执行依赖任务?
- javascript - 修改 CSS 属性时使用变量时出现问题
- sql - 我在 GridDB 中运行查询,但没有任何反应
- ruby-on-rails - 在设置狂欢商务时遇到问题
- postgresql - 备份一个数据库中的模式并使用转储在另一个数据库中恢复具有不同名称的相同模式
- jquery - 使用背景位置滚动背景图像视差:底部
- wordpress - 对齐 woo 商务产品添加到购物车按钮
- javascript - react-native Metro 错误“无法构建变压器”