[英]How do you count a tuple list and export the frequency of the variables into a dictionary?
我一直在研究一種分配的解決方案,其中我們接受一個元組對象列表並返回一個包含該列表中所有字符串出現頻率的字典
所以我一直在嘗試使用Collection中的Counter來計算元組列表中出現的鍵的頻率
tuple_list = [('a',5), ('a',5), ('b',6), ('b',4), ('b',3), ('b',7)]
我不能讓Counter僅檢查'a'或'b'還是僅檢查列表中的字符串。
from collections import Counter
def get_frequency(tuple_list):
C = Counter(new_list)
print (C('a'), C('b'))
tuple_list = [('a',5), ('a',5), ('b',6), ('b',4), ('b',3), ('b',7)]
freq_dict = get_frequency(tuple_list)
for key in sorted(freq_dict.keys()):
print("{}: {}".format(key, freq_dict[key]))
我期望的輸出應該是a: 2 b: 4
但是我一直得到a: 0 b: 0
由於每個元組中的第二個(數字)元素似乎無關緊要,因此您需要傳遞要計算的字母序列。 嘗試列表理解:
>>> tuple_list = [('a',5), ('a',5), ('b',6), ('b',4), ('b',3), ('b',7)]
>>>
>>> items = [item[0] for item in tuple_list]
>>> items
['a', 'a', 'b', 'b', 'b', 'b']
>>> from collections import Counter
>>> c = Counter(items)
>>> print(c)
Counter({'b': 4, 'a': 2})
如果您不想使用計數器,則可以像這樣使用列表的長度...
unique_values = list(set([x[0] for x in tuple_list]))
a_dict = {}
for v in unique_values:
a_dict[v] = len([x[1] for x in tuple_list if x[0] == v])
print(a_dict)
這給你:
{'b': 4, 'a': 2}
由於只希望對每個元組中的第一個元素(字符串)進行計數,因此,僅應在該第一個元素上使用counter對象,如下面的get_frequency函數所示:
def get_frequency(tuple_list):
cnt = Counter()
for tuple_elem in tuple_list:
cnt[tuple_elem[0]] += 1
return cnt
tuple_list = [('a',5), ('a',5), ('b',6)]
freq_dict = get_frequency(tuple_list)
for key, value in freq_dict.items():
print(f'{key}: {value}')
另外,請確保如果希望從函數接收值,則通常需要使用return語句返回值。
希望有幫助!
另一個解決方案是使用zip
, next
使用next
將每個元組的第一項提取到新的元組中,並將其輸入Counter
。
from collections import Counter
result = Counter(next(zip(*items)))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.