简体   繁体   English

如何计算元组列表并将变量的频率导出到字典中?

[英]How do you count a tuple list and export the frequency of the variables into a dictionary?

I've been working on a solution for an assignment where we which accepts a list of tuple objects and returns a dictionary containing the frequency of all the strings that appear in the list 我一直在研究一种分配的解决方案,其中我们接受一个元组对象列表并返回一个包含该列表中所有字符串出现频率的字典

So I've been trying to use Counter from collections to count the frequency of a key that is occurring inside a tuple list 所以我一直在尝试使用Collection中的Counter来计算元组列表中出现的键的频率

tuple_list = [('a',5), ('a',5), ('b',6), ('b',4), ('b',3), ('b',7)]

I can't get the Counter to only check for 'a' or 'b' or just the strings in the list. 我不能让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]))

The output that I was expecting should be a: 2 b: 4 but I kept on getting a: 0 b: 0 我期望的输出应该是a: 2 b: 4但是我一直得到a: 0 b: 0

Since the second (numeric) element in each tuple appears to be irrelevant, you need to pass in a sequence of the letters you're trying to count. 由于每个元组中的第二个(数字)元素似乎无关紧要,因此您需要传递要计算的字母序列。 Try a list comprehension: 尝试列表理解:

>>> 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})

if you don't want to use counter, you can just do the length of the lists like this... 如果您不想使用计数器,则可以像这样使用列表的长度...

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)

which gives you: 这给你:

{'b': 4, 'a': 2}

Since you only want to count the first element (the string) in each tuple, you should only use the counter object on that first element as you can see in the get_frequency function below: 由于只希望对每个元组中的第一个元素(字符串)进行计数,因此,仅应在该第一个元素上使用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}')

Also, make sure if you hope to receive a value from a function, you usually need to return a value using a return statement. 另外,请确保如果希望从函数接收值,则通常需要使用return语句返回值。

Hope that helps out! 希望有帮助!

Another solution is to use zip and next to extract the first item of each tuple into a new tuple and feed it into Counter . 另一个解决方案是使用zipnext使用next将每个元组的第一项提取到新的元组中,并将其输入Counter

from collections import Counter
result = Counter(next(zip(*items)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM