添加单个字符在计数器中添加键 [英] Adding a single character to add keys in Counter
问题描述
如果Counter对象的键的类型是 str
,即:
If the type of a Counter object's keys is str
, i.e.:
我可以这样做: / p>
I could do this:
>>> vocab_counter = Counter("the lazy fox jumps over the brown dog".split())
>>> vocab_counter = Counter({k+u"\uE000":v for k,v in vocab_counter.items()})
>>> vocab_counter
Counter({'brown\ue000': 1,
'dog\ue000': 1,
'fox\ue000': 1,
'jumps\ue000': 1,
'lazy\ue000': 1,
'over\ue000': 1,
'the\ue000': 2})
向所有键添加字符将是一种快速和/或pythonic的方式?
上述方法是使用所有键附加字符来实现最终计数器的唯一方法?有没有其他方式来实现同样的目标?
Is the above method the only way to achieve the final counter with the character appended to all keys? Are there other way(s) to achieve the same goal?
推荐答案
更好的方法是在创建计数器之前添加该字符目的。您可以使用计数器
中的生成器表达式:
The better way would be adding that character before creating your counter object. You can do it using a generator expression within Counter
:
In [15]: vocab_counter = Counter(w + u"\uE000" for w in "the lazy fox jumps over the brown dog".split())
In [16]: vocab_counter
Out[16]: Counter({'the\ue000': 2, 'fox\ue000': 1, 'dog\ue000': 1, 'jumps\ue000': 1, 'lazy\ue000': 1, 'over\ue000': 1, 'brown\ue000': 1})
如果在创建计数器之前无法修改单词,您可以覆盖计数器
对象,以添加特殊字符在设置密钥的值。
If it's not possible to modify the words before creating the Counter you can override the Counter
object in order to add the special character during setting the values for keys.
这篇关于添加单个字符在计数器中添加键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!