dict.setDefault:仅在不存在的情况下,仅消耗迭代器
代码的某些片段看起来像这样(这是问题的删除版本):
y = dict()
it = iter([1,2,3])
y.setdefault(23, next(it))
y.setdefault(42, next(it))
y.setdefault(42, next(it))
y.setdefault(1337, next(it)) # throws StopIteration
# The result should look like this:
# {23: 1, 42: 2, 1337: 3}
基本上,有一些迭代器,我想使用setDefault
在该迭代器中使用setDefault
填充字典但是,只有以前的字典中不存在该值。显然,在这种情况下,它失败了,因为next()
被称为4次,即使只有3个唯一值可以放入dict中。
一种解决方案可能是简单地编写检查函数或进行检查的类:
def setdefault(d, k, v):
if k in d:
return d[k]
return d.setdefault(k, next(v))
或者
class mydict(dict):
def it_setdefault(self, k, i):
if k in self:
return self[k]
return self.setdefault(k, next(i))
,我想知道是否有类似的字典可以使用?
Some fragment of a code looks like this (this is a stripped down version of the problem):
y = dict()
it = iter([1,2,3])
y.setdefault(23, next(it))
y.setdefault(42, next(it))
y.setdefault(42, next(it))
y.setdefault(1337, next(it)) # throws StopIteration
# The result should look like this:
# {23: 1, 42: 2, 1337: 3}
Basically, there is some iterator and I would like to fill a dictionary using setdefault
with the next value in that iterator but only if the value did not exist in the dictionary before. Obviously in this case it fails because next()
is called 4 times, even though there are only 3 unique values to put into the dict.
One solution could be to simply write a function or a class that does the check:
def setdefault(d, k, v):
if k in d:
return d[k]
return d.setdefault(k, next(v))
or
class mydict(dict):
def it_setdefault(self, k, i):
if k in self:
return self[k]
return self.setdefault(k, next(i))
However, I wonder if there is something like this already available for dictionaries?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论