为namedtuple添加一些东西

时间:2012-04-27 21:18:58

标签: python

我建立

Corpus = collections.namedtuple('Corpus', 'a, b, c, d')

阅读语料库中的所有文件并保存数据,

def compute(counters, tokens, catergory)
    ...
    counters.stats[tokens][catergory] = Corpus(a, b, c, d)

令牌和catergory都是collection.Counter()。在读取了counter.stats中a,b,c,d中的所有信息后,我在另一个函数中进行了一些计算,并为每个标记获得“e”。如何在此函数中将counter添加到counter.stats?

1 个答案:

答案 0 :(得分:3)

如果你正在谈论将'e'添加到counter.stats[tokens][category]的语料库命名元组中,那么这是不可能的,因为命名元组是不可变的。您可能必须使用a b c d e值创建一个新的namedtuple,并将其分配给counter.stats [tokens] [category]。下面的代码是一个例子:

>>> from collections import namedtuple
>>> two_d = namedtuple('twoDPoint', ['x', 'y'])
>>> x = two_d(1, 2)
>>> x = two_d(1, 2)
>>> three_d = namedtuple('threeDPoint', ['x', 'y', 'z'])
>>> x
twoDPoint(x=1, y=2)
>>> y = three_d(*x, z=3)
>>> y
threeDPoint(x=1, y=2, z=3)