如何在功能上编写此表达式? [英] How to write this expression functionally?

查看:65
本文介绍了如何在功能上编写此表达式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在功能上重写以下python代码:

I want to rewrite the following python code functionally:

lst = [0.0] * 10
for pos in [2,5]:
    lst[pos] = 1.0

这是我的尝试,但不正确:

This is my attempt, but is incorrect:

lst = (lambda zeros:
          map(
              lambda pos: zeros[pos] = 1.0, [2,5])
      )([0.0] * 10)

我得到的错误是 lambda无法包含赋值.

使用列表理解,解决方案是:

Using list comprehension, the solution is:

lst = [ 1.0 if x in [2,5] else 0.0 for x in range(10) ]

推荐答案

在您自己的答案中,我确实更喜欢列表理解,但是如果我要在功能上进行一些尝试,我想我会使用 lambda 函数和 map :

I do prefer the list comprehension in your own answer, but if I were to do it with more of a functional touch, I think I would use a lambda function and a map:

lazy = map(lambda element: 1 if element in [2,5] else 0, range(10))

请注意, map 是Python 3中的一个惰性迭代器.如果要获得评估的 list ,则必须将该行括在显式的 list(..中..)构造函数:

Note that map is a lazy iterator in Python 3. If you want an evaluated list you have to enclose the line in an explicit list(...) constructor:

lst = list(map(lambda element: 1 if element in [2,5] else 0, range(10)))

这篇关于如何在功能上编写此表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆