Python 函数获取整数列表并计算最高重复值
需要一个函数来获取整数列表并返回最高的重复值 例如:获取[4,2,2,8,5,4,2,9,6,3,2]并返回2,5,因为值2有5个副本。您可以使用defaultdict实现这一点:Python 函数获取整数列表并计算最高重复值,python,arrays,list,Python,Arrays,List,需要一个函数来获取整数列表并返回最高的重复值 例如:获取[4,2,2,8,5,4,2,9,6,3,2]并返回2,5,因为值2有5个副本。您可以使用defaultdict实现这一点: from collections import defaultdict def highest_repeated_value(nums): cache = defaultdict(int) for i in nums: cache[i] += 1 return max(cache.items()
from collections import defaultdict
def highest_repeated_value(nums):
cache = defaultdict(int)
for i in nums:
cache[i] += 1
return max(cache.items(), key=lambda x: x[1])
nums = [4, 2, 2, 2, 8, 5, 4, 2, 9, 6, 3, 2]
print(highest_repeated_value(nums))
请注意,如果nums=[4,4,4,2,2,8,5,4,2,9,6,3,2],则有五个4和五个2。但是,结果将是4,5,即5个4
如果使用numpy和列表包含所有非负整数,则可以使用numpy.bincounts:
如果您只想在python中工作而不使用numpy,那么collections.Counter是一种很好的处理方法
from collections import Counter
def highest_repeated_value(nums):
return Counter(nums).most_common()[0]
nums = [4, 2, 2, 2, 8, 5, 4, 2, 9, 6, 3, 2]
print(highest_repeated_value(nums))
使用计数器可以很容易地完成此操作
from collections import Counter
a = [4, 2, 2, 2, 8, 5, 4, 2, 9, 6, 3, 2]
def count_duplicates(list_of_integers):
a = Counter(list_of_integers)
return a.most_common()[0]
count = count_duplicates(a)
print(count)
它的输出为您提供了2,5个内置的最大值、设置和计数方法:
打印2,5。我们可以利用tuple跟踪最高重复值,如下所示:
def find_highest_repeated(input_list):
counter = {}
highest_repeated = (0, 0, )
for item in input_list:
counter[item] = counter[item] + 1 if counter.get(item) is not None else 1
if counter[item] > highest_repeated[1]:
highest_repeated = (item, counter[item], )
return highest_repeated
find_highest_repeated([4, 2, 2, 2, 8, 5, 4, 2, 9, 6, 3, 2]) # (2, 5)
希望有帮助 有没有办法用numpy来完成这个任务?欢迎使用。请花点时间阅读和阅读该页面上的其他链接。这不是一个讨论论坛或教程服务。你应该花一些时间来练习这些例子。它将向您介绍Python为解决您的问题所提供的工具。
def countMax(arr):
item = max(set(arr), key=arr.count)
return (item, arr.count(item))
print(countMax([4, 2, 2, 2, 8, 5, 4, 2, 9, 6, 3, 2]))
def find_highest_repeated(input_list):
counter = {}
highest_repeated = (0, 0, )
for item in input_list:
counter[item] = counter[item] + 1 if counter.get(item) is not None else 1
if counter[item] > highest_repeated[1]:
highest_repeated = (item, counter[item], )
return highest_repeated
find_highest_repeated([4, 2, 2, 2, 8, 5, 4, 2, 9, 6, 3, 2]) # (2, 5)