【问题标题】:I need to create a function that filters a list without a for loop [closed]我需要创建一个函数来过滤没有 for 循环的列表 [关闭]
【发布时间】:2019-01-03 11:10:06
【问题描述】:

所以我的函数需要过滤一个列表,以便它只返回一个列表,该列表仅包含在将函数应用于它而不使用任何循环时返回正值的值。我的代码目前是:

def positive_places(f, xs):
    """takes a function f and list xs and returns
    a list of the values of xs which satisfy
    f>0"""
    y = list(map(f, xs))
    x = filter(lambda i: i > 0, y)
    return x

这当前返回函数的所有正输出值的列表,但是我需要原始列表 xs 中的对应值。

提前感谢您的帮助!

【问题讨论】:

  • “但是我需要原始列表 xs 中的相应值”是什么意思?意思是,你能解释一下吗?
  • 为什么不能使用 for 循环?列表组合是这里最干净的解决方案

标签: python python-3.x


【解决方案1】:

使用list comprehension

return [x for x in xs if f(x) > 0]

不使用列表推导:

return filter(lambda x: f(x) > 0, xs)

既然你说它应该返回一个列表:

return list(filter(lambda x: f(x) > 0, xs))

【讨论】:

  • OP:“但是列表推导有 for 循环!”
  • 我会走这条路,但正如我所说,我不能使用任何循环
【解决方案2】:

使用递归有两种可能的解决方案,它们不使用循环或推导 - 在内部实现迭代协议。

方法一:

lst = list()


def foo(index):
    if index < 0 or index >= len(xs):
        return
    if f(xs[index]) > 0:
        lst.append(xs[index])
        # print xs[index] or do something else with the value
    foo(index + 1)


# call foo with index = 0

方法二:

lst = list()


def foo(xs):
    if len(xs) <= 0:
        return
    if f(xs[0]) > 0:
        lst.append(xs[0])
    foo(xs[1:])


# call foo with xs

这两种方法都会创建一个包含所需值的新列表。第二种方法使用列表切片,我不确定内部是否实现了迭代协议。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-11
    • 2021-12-21
    • 2013-06-03
    • 2019-12-20
    • 1970-01-01
    • 2019-05-03
    • 2021-09-22
    • 1970-01-01
    相关资源
    最近更新 更多