使用Python中的字典计算列表中的频率
给定一些元素的未排序列表(可能是整数,也可能不是整数),使用字典查找列表中每个不同元素的频率。
例子:
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 : 2
Explanation : 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)
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)
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
2 : 4
3 : 3
4 : 3
5 : 2
时间复杂度: O(N),其中 N 是列表的长度。
另一种方法:另一种方法是使用 list.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 是列表的长度。时间复杂度 list.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}
相关文章:
使用集合模块计算Python中数组中所有元素的频率