[英]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.