【问题标题】:adjusting python autoviv to take "+=1" increments调整 python autoviv 以采用“+=1”增量
【发布时间】:2017-11-14 06:05:07
【问题描述】:

我正在使用一些常见的python自动生成代码构建字典:

class autoviv(dict):
    """Implementation of perl's autovivification feature."""

    def __getitem__(self, item):  
        try:
            return dict.__getitem__(self, item)
        except KeyError:     
            value = self[item] = type(self)()
            return value

我希望能够做的一件事是在指定的字典嵌套级别当前不存在键的情况下增加值,使用 += 表示法,如下所示:

d['a']+=1

这样做会返回错误:

TypeError: unsupported operand type(s) for +=: 'autoviv' and 'int'

为了解决这个问题,我构建了一个步骤,在递增之前检查密钥是否存在,但如果可以的话,我很想取消该步骤。

我应该如何修改上面的 autoviv() 代码来获得这个增强功能?我已经用谷歌搜索并尝试了几个小时的不同方法,但没有任何乐趣。

感谢您的建议!

【问题讨论】:

  • d["a"] 返回什么?
  • 抱歉。上述 autoviv 的工作方式是:最小输入为“d['a']=X (e.g. 1)”。如果 "d['a']" 还不存在,它将在 dict 中创建该键并将其值设置为您指定的数字,如 {a:1}。只有当密钥已经存在时,才可以使用“d['a']+=1”。现在,如果密钥不存在并且您使用 +=1 ,则会引发错误。我想做的是,对于不存在的密钥,使用“d['a']+=1”并自动创建 k:v 对而不会引发错误。感谢您的回复!

标签: python autovivification


【解决方案1】:

Autovivication 已经在 Python 中,位于 collections' defaultdict 中。

from collections import defaultdict


#Let's say we want to count every character
#  that occurs
text = "Let's implement autovivication!"
di = defaultdict(int)
for char in text:
    di[char] += 1
print(di)

#Another way of doing this is using a defualt string
#  (or default int, or whatever you want)
currentDict = {'bob':'password','mike':'12345'}
di = defaultdict(lambda:'unknown user', currentDict)
print(di['bob'])
print(di['sheryl'])

但是,如果您尝试实现自己的。您应该分配您的项目,然后获取对它的引用。

def __getitem__(self, item):  
    try:
        return dict.__getitem__(self, item)
    except KeyError:
        value = self[item] = type(self)()        
        return dict.__getitem__(self, item)

【讨论】:

  • 谢谢!但是:from collections import defaultdict d=defaultdict(int) d['a']['v']+=1 给了我“TypeError: 'int' object has no attribute 'getitem'”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-25
  • 2016-02-13
  • 1970-01-01
  • 1970-01-01
  • 2018-06-21
  • 2014-12-23
相关资源
最近更新 更多