gpt4 book ai didi

python - 在 lambda 中使用 __iadd__?

转载 作者:太空狗 更新时间:2023-10-30 01:45:29 29 4
gpt4 key购买 nike

我试图解决这个小挑战:

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 中做到这一点?更新可变默认参数并返回?

最佳答案

有两个问题:

  1. ... += ... 是语句,不是表达式。您可以显式调用 __iadd__except ...
  2. 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/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com