【问题标题】:Python, using lambda, map and filterPython,使用 lambda、map 和 filter
【发布时间】:2018-06-27 14:00:10
【问题描述】:

E 是 a、b、c 和 d 的组合。 D是最终结果。 所以 e 的结果应该和 d 一样。但事实并非如此。我做错了什么?

d = [24, 42, 30, 42, 48, 36] 的结果

e = [42, 42, 48, 36] 的结果

numbers = [2,4,7,2,5,3,7,8,1,6]

def mapping():
    a = list(filter(lambda x : x > 3, numbers))
    print(a)
    b = list(map(lambda x : x * 3, a))
    print(b)
    c = list(filter(lambda x : x > 10, b))
    print(c)
    d = list(map(lambda x : x * 2, c))
    print(d)

    e = list(filter(lambda x : x > 3, map(lambda x : x * 3, filter(lambda x : x > 10, map(lambda x : x * 2, numbers)))))
    print(e)
mapping()

【问题讨论】:

  • 您的过滤顺序不同。
  • filters for e 被应用 inside-out。意思是,首先应用lambda x : x > 10。本质上,e 遵循相反的顺序。

标签: python list lambda filter mapping


【解决方案1】:

问题在于,当您计算 e 时,按照与计算 d 时相反的顺序执行操作。尝试像这样计算e:

e = list(map(lambda x : x * 2, 
             filter(lambda x : x > 10, 
                    map(lambda x : x * 3, 
                        filter(lambda x : x > 3, numbers)))))

【讨论】:

  • 时尚回答。使用列表理解,它看起来像e = [ 2*y for y in [ 3*x for x in numbers if x > 3 ] if y > 10 ]。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-06-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-08
  • 1970-01-01
相关资源
最近更新 更多