【问题标题】:Using filter to iterate over a list使用过滤器遍历列表
【发布时间】:2014-12-31 12:38:14
【问题描述】:

因此,我被要求使用 filter() 函数在列表上迭代函数,以便在应用函数后仅在列表中返回正值。 到目前为止,我有这个:

def positive_place(f, xs)
    ans = filter(lambda x: f(x) > 0, xs)
    return ans

有人特别要求我不要使用for 循环(尽管我更愿意这样做)。我对filter() 不太熟悉,如果有人能告诉我哪里出错了,我将不胜感激。上面的函数只是返回我提供的列表中的正值。

【问题讨论】:

  • 你传递的函数f是什么定义的?

标签: list loops filter lambda


【解决方案1】:

您的filter 功能正确。但是有一些错误:

  • 函数定义错误。最后应该包含一个:。赞def positive_place(f, xs):

  • 如果您使用的是 Python 3,它会返回一个过滤器对象。因此,您必须将其转换为列表。赞return list(ans)

你的程序看起来像

def positive_place(f, xs):    
    ans = filter(lambda x: f(x) > 0, xs)
    return list(ans)

【讨论】:

    猜你喜欢
    • 2016-01-09
    • 2021-12-25
    • 2021-09-13
    • 2013-01-24
    • 2018-10-12
    • 1970-01-01
    • 2020-04-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多