识别列表 python 中最少的常见数字



有了数字列表,每个数字可以出现多次,我需要在列表中找到最不常见的数字。如果不同的数字具有相同的最低频率,则结果是列表中最后出现的数字。例如,[1, 7, 2, 1, 2] 中最不常见的整数是 7(而不是最初所说的 2)。并且列表需要保持未排序

我有以下内容,但它总是将最后一个条目设置为 minimumCommon

def least_common_in_unsorted(integers):
    leastCommon = integers[0]
    check = 1
    appears = 1
    for currentPosition in integers:
        if currentPosition == leastCommon:
            appears + 1
        elif currentPosition != leastCommon:
            if check <= appears:
                check = 1
                appears = 1
                leastCommon = currentPosition
    return leastCommon

任何帮助将不胜感激

这是我现在想到的最简单的方法:

a = [1, 7, 2, 1, 2]
c, least = len(a), 0
for x in a:
    if a.count(x) <= c :
        c = a.count(x)
        least = x
least # 7

在最少的两个项目中,它将返回最后一个出现的项目。

a = [1, 7, 2, 1, 2, 7] # least = 7

使用计数器:

from collections import Counter
lst = [1, 7, 2, 1, 2]
cnt = Counter(lst)
mincnt = min(cnt.values())
minval = next(n for n in reversed(lst) if cnt[n] == mincnt)
print(minval) #7

此答案基于@offtoffel,即在选择最后一个出现的项目时合并相同次数的多个项目:

def least_common(lst):   
    return min(lst, key=lambda x: (lst.count(x), lst[::-1].index(x)))

print(least_common([1,2,1,2]))
# 2
print(least_common([1,2,7,1,2]))
# 7

编辑:我注意到有一个更简单的解决方案,它是高效和有效的(只需在开始时反转列表,min 将保留具有最小计数的最后一个值):

def least_common(lst): 
    lst = lst[::-1]
    return min(lst, key=lst.count)

print(least_common([1,2,1,2]))
# 2
print(least_common([1,2,7,1,2]))
# 7

简短但效率低下:

>>> min(a[::-1], key=a.count)
7

使用集合的高效版本。计数器:

>>> min(a[::-1], key=Counter(a).get)
7
def least_common(lst):
    return min(set(lst), key=lst.count)

编辑:抱歉,这并不总是按照用户的要求,以最少的出现次数获取最后一个列表项......它适用于示例,但并非适用于所有实例。

最新更新