给定一些元素(可能是整数,也可能不是整数)的未排序列表,使用字典查找列表中每个不同元素的频率。 例子:
null
Input : [1, 1, 1, 5, 5, 3, 1, 3, 3, 1, 4, 4, 4, 2, 2, 2, 2]Output : 1 : 5 2 : 4 3 : 3 4 : 3 5 : 2Explanation : Here 1 occurs 5 times, 2 occurs 4 times and so on...
这个问题可以用很多方法解决。一种简单的方法是迭代列表,使用列表中的每个不同元素作为字典的键,并将该键的相应计数存储为值。下面是这种方法的Python代码:
python
# Python program to count the frequency of # elements in a list using a dictionary def CountFrequency(my_list): # Creating an empty dictionary freq = {} for item in my_list: if (item in freq): freq[item] + = 1 else : freq[item] = 1 for key, value in freq.items(): print ( "% d : % d" % (key, value)) # Driver function if __name__ = = "__main__" : my_list = [ 1 , 1 , 1 , 5 , 5 , 3 , 1 , 3 , 3 , 1 , 4 , 4 , 4 , 2 , 2 , 2 , 2 ] CountFrequency(my_list) |
输出:
1 : 5 2 : 4 3 : 3 4 : 3 5 : 2
时间复杂性: O(N),其中N是列表的长度。
替代方法: 另一种方法是使用列表。count()方法。
python
# Python program to count the frequency of # elements in a list using a dictionary def CountFrequency(my_list): # Creating an empty dictionary freq = {} for items in my_list: freq[items] = my_list.count(items) for key, value in freq.items(): print ( "% d : % d" % (key, value)) # Driver function if __name__ = = "__main__" : my_list = [ 1 , 1 , 1 , 5 , 5 , 3 , 1 , 3 , 3 , 1 , 4 , 4 , 4 , 2 , 2 , 2 , 2 ] CountFrequency(my_list) |
输出:
1 : 5 2 : 4 3 : 3 4 : 3 5 : 2
时间复杂性: O(N) 2. ),其中N是列表的长度。时间复杂性列表。count()单独是O(N),当在循环中使用时,它将变成O(N) 2. ).
替代方法: 另一种方法是使用dict.get()方法。这使程序变得更短,并使我们了解get方法如何比if…else更有用。
python
# Python program to count the frequency of # elements in a list using a dictionary def CountFrequency(my_list): # Creating an empty dictionary count = {} for i in [ 1 , 1 , 1 , 5 , 5 , 3 , 1 , 3 , 3 , 1 , 4 , 4 , 4 , 2 , 2 , 2 , 2 ]: count[i] = count.get(i, 0 ) + 1 return count # Driver function if __name__ = = "__main__" : my_list = [ 1 , 1 , 1 , 5 , 5 , 3 , 1 , 3 , 3 , 1 , 4 , 4 , 4 , 2 , 2 , 2 , 2 ] print (CountFrequency(my_list)) |
输出:
{1: 5, 5: 2, 3: 3, 4: 3, 2: 4}
相关文章: 使用collections模块计算Python中数组中所有元素的频率
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END