defaultdict,带有类构造函数的参数

时间:2010-11-10 00:03:00

标签: python collections dictionary python-3.x

[Python 3.1]

我想要defaultdict(int),但我希望默认值为1而不是0

  1. 有什么好办法吗?
  2. 我应该这样做吗?

4 个答案:

答案 0 :(得分:14)

>>> def f():
        return 1
>>> a = defaultdict(f)
>>> a[1]
1

这是使用lambda表达式的另一个实现(来自 kindall ):

>>> a = defaultdict(lambda: 1)

答案 1 :(得分:4)

defaultdict(lambda: 1)

例如

>>> from collections import defaultdict
>>> a = defaultdict(lambda: 1)
>>> a["foo"] += 1
>>> a["foo"]
2

答案 2 :(得分:1)

来自文档:

始终返回零的函数int()只是常量函数的特例。创建常量函数的更快更灵活的方法是使用itertools.repeat(),它可以提供任何常量值(而不仅仅是零):

>>> def constant_factory(value):
...     return itertools.repeat(value).next
>>> d = defaultdict(constant_factory('<missing>'))
>>> d.update(name='John', action='ran')
>>> '%(name)s %(action)s to %(object)s' % d
'John ran to <missing>'

答案 3 :(得分:0)

使用partial,您可以创建具有默认参数的函数:

from functools import partial
from collections import defaultdict

int1 = partial(int, 1)
mydict = defaultdict(int1)
mydict[1]

并且类的行为类似于创建对象的函数。

也可以使用关键字参数,例如:

from functools import partial
from collections import defaultdict

class Rectangle:

   def __init__(x, y, l=10, h=20):
      self.x = x
      self.y = y
      self.l = l
      self.h = h

TopSquare30 = partial(Rectangle, 0, 0, l=30, h=30)

rectangles = defaultdict(TopSquare30)
john_square = rectangles['john']
paul_square = rectangles['paul']

请注意,这里的默认参数将始终具有执行partial时给出的值。

关于lambda或函数的其他答案将使用在创建对象时计算出的值。