- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我试图解决这个小挑战:
You want a defaultdict that uses a different value every time a non-existent key is looked up, i.e. a counter; 1 for the first non-existent key, 2 for the second, etc.
我是这样解决的:
from collections import defaultdict
def f(a=[0]):
a[0]+=1
return a[0]
s=defaultdict(f)
奖励是尝试在一行中完成此操作。
s=defaultdict(lambda a=[0]: (a[0]+=1))
SyntaxError: invalid syntax _________^
有没有办法在 lambda 中做到这一点?更新可变默认参数并返回?
最佳答案
有两个问题:
... += ...
是语句,不是表达式。您可以显式调用 __iadd__
,except ...int
没有定义 __iadd__
; a[0] += 1
只是实现为 a[0] = a[0] + 1
。您需要做的是显式调用 __setitem__
来更新默认列表值的第 0 个元素。这将返回 None
,而不是 a[0]
,因此您还需要一个 or
表达式来返回 a[ 0]
(因为 None 或 x == x
):
>>> s = defaultdict(lambda a=[0]: a.__setitem__(0, a[0] + 1) or a[0])
>>> s[6]
1
>>> s[9]
2
>>> s[6]
1
>>> s[8]
3
(我会自己写 defaultdict(itertools.count(0).__next__)
。)
关于python - 在 lambda 中使用 __iadd__?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55937784/
我想子类化一个不可变类型或实现我自己的一个,其行为类似于 int,如以下控制台 session 所示: >>> i=42 >>> id(i) 10021708 >>> i.__iadd__(1) Tr
我对 python (一般来说是 oop) 很陌生,我想知道对 __iadd__ 的期望是什么。是。它应该创建一个新对象还是修改现有对象? 因此,如果我考虑一类分数并使用 += 添加两个分数: q1
我注意到列表扩展返回值有一些奇怪的行为。 我已阅读此主题 Why does += behave unexpectedly on lists? 但是还是没有意义。 这是我做的: Python 3.5.2
我有一些短类 Car: class Car: def __init__(self, brand, model, color, accesories): self.brand =
对于“更好”的更简单的代码,我想知道是否可以执行保留/反射的增强加法分配。 [我已经检查了 Stack Overflow 上是否有类似的问题,但找不到任何问题。因此,如果这是重复我的道歉,请链接答案。
This question处理 Python 读写属性的 __iadd__。但是,我正在努力寻找只读属性的解决方案。 在我的 MWE 中,我们有一个只读属性 Beta.value,返回一个 Alpha
我知道这是不好的做法: >>> a = 5 >>> a.__radd__(5) 10 >>> a 5 >>> a.__iadd__(5) Traceback (most recent call las
我试图解决这个小挑战: You want a defaultdict that uses a different value every time a non-existent key is look
这个问题在这里已经有了答案: Handling of duplicate indices in NumPy assignments (5 个答案) numpy: efficiently summin
我正在尝试创建一个 Python 属性,其中就地添加是通过与检索值、添加另一个值和重新分配不同的方法来处理的。因此,对于对象 o 上的属性 x, o.x += 5 应该不同于 o.x = o.x +
关于这个奇怪的事情有什么想法吗? from numpy import * a = array([1,2]) b = 1 b += a 给出 array([2,3]),如您所料。但是 a = array
谁能告诉我为什么这段代码提示容器上没有 __setitem__?我以为我只需要容器上的 __getitem__ 来获取项目,然后 __iadd__ 来设置值,不知道为什么它期待 __setitem__
尝试修 retrofit 饰器不以使用weakref,我偶然发现了以下行为: import weakref class descriptor(object): def __get__(self
我刚刚进行了一个有趣的测试: ~$ python3 # I also conducted this on python 2.7.6, with the same result Python 3.4.0
python的documentation on the methods related to the in-place operators类似于+=和*=(或者,正如它所说的,增加的算术赋值)有以下说
是否可以在 Python 中覆盖 +=? 最佳答案 是的,覆盖 __iadd__方法。示例: def __iadd__(self, other): self.number += other.n
这个问题在这里已经有了答案: UnboundLocalError trying to use a variable (supposed to be global) that is (re)assig
考虑以下代码: >>> x = y = [1, 2, 3, 4] >>> x += [4] >>> x [1, 2, 3, 4, 4] >>> y [1, 2, 3, 4, 4] 然后考虑一下: >>
使用以下代码: class X( object ): def __init__( self ): self.value = 0 def __iadd__( self,
使用以下代码: class X( object ): def __init__( self ): self.value = 0 def __iadd__( self,
我是一名优秀的程序员,十分优秀!