[英]how can i store the printing result, obtained by “for statement” variable?
我正在计算一些特定的双字词频率。 以下是我的代码的一部分。
sorted_bigrams = sorted(bigrams.items(), key = lambda pair:pair[1], reverse = True)
for bigram, count in sorted_bigrams:
if bigram == ("interesting", "news"):
print count
在这里,我要存储打印结果“ count”的计数,这是二元组“有趣,新闻”的计数
我该怎么做..
如果要存储总数:
sorted_bigrams = sorted(bigrams.items(), key = lambda pair:pair[1], reverse = True)
total_count = 0
for bigram, count in sorted_bigrams:
if bigram == ("interesting", "news"):
print count
total_count += count
print total_count
如果要跟踪计数明细,请执行以下操作:
sorted_bigrams = sorted(bigrams.items(), key = lambda pair:pair[1], reverse = True)
counts = []
for bigram, count in sorted_bigrams:
if bigram == ("interesting", "news"):
print count
counts.append(count)
print counts
如果bigrams
是一个将bigram作为键存储并作为值计数的字典,则由于键是唯一的,因此无需对其进行排序即可获得总计数。
如果bigrams
是元组列表,则可以使用collections.Counter
获取总计数。
In [30]: bigrams
Out[30]: [(('a', 'b'), 10), (('d', 'f'), 3), (('a', 'c'), 15), (('a', 'b'), 2)]
In [31]: counter = Counter()
In [32]: for key, val in bigrams:
counter[key] += val
....:
In [33]: counter[('a', 'b')]
Out[33]: 12
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.