在 lambda 函数中设置 numpy 切片
我想创建一个 lambda 函数,它接受两个 numpy 数组并将第一个数组的切片设置为第二个数组,然后返回新设置的 numpy 数组。
考虑到你不能在 lambda 函数中分配东西,有没有办法做类似的事情?
其上下文是我想在一行中将零数组的中心设置为另一个数组,而我能想到的唯一解决方案是使用reduce 和lambda 函数。
即我正在考虑将其压缩(其中给出了 b):
a = numpy.zeros( numpy.array(b.shape) + 2)
a[1:-1,1:-1] = b
压缩成一行。这可能吗? 这只是单线练习。我有代码做我想做的事情,我只是想知道这个是为了它的乐趣:)。
I want to create a lambda function that takes two numpy arrays and sets a slice of the first to the second and returns the newly set numpy array.
Considering you can't assign things in lambda functions is there a way to do something similar to this?
The context of this is that I want to set the centre of a zeros array to another array in a single line, and the only solution I could come up with is to use reduce and lambda functions.
I.e. I'm thinking about the condensation of this (where b is given):
a = numpy.zeros( numpy.array(b.shape) + 2)
a[1:-1,1:-1] = b
Into a single line. Is this possible?
This is just an exercise in oneliners. I have the code doing what I want it to do, I'm just wondering about this for the fun of it :).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这很丑陋;你不应该使用它。但正如您所问的,它是 oneline lambda:
什么是 __setitem__ ?
在这种情况下,
obj.__setitem__(index, value)
相当于obj[index] = value
。示例:它打印:
Why does
__setitem__()
return None?Python 中有一个通用约定,即就地修改对象的
list.extend()
、list.append()
等方法应返回None< /代码>。但也有例外,例如
list.pop()
。Python 中的 Y 组合器
这是博客文章 关于编写 Python one- liners 展示了如何使用 lambda 编写无名递归函数(该链接由 @Peter Hansen 建议)。
This is ugly; you should not use it. But it is oneline lambda as you've asked:
What is
__setitem__
?obj.__setitem__(index, value)
is equivalent toobj[index] = value
in this case. Example:It prints:
Why does
__setitem__()
return None?There is a general convention in Python that methods such as
list.extend()
,list.append()
that modify an object in-place should returnNone
. There are exceptions e.g.,list.pop()
.Y Combinator in Python
Here's blog post On writing Python one-liners which shows how write nameless recursive functions using
lambda
s (the link is suggested by @Peter Hansen).