Python 确定列表中最不常见的数字
对于数字列表,每个数字可以出现多次,我需要找到列表中最不常见的数字。如果不同的数字具有相同的最低频率,则结果是列表中最后出现的数字。例如,[1,7,2,1,2]中最不常见的整数是7(而不是原来所说的2)。而且名单需要保持不分类 我有以下内容,但它总是将最后一个条目设置为leastCommonPython 确定列表中最不常见的数字,python,python-2.7,python-3.x,Python,Python 2.7,Python 3.x,对于数字列表,每个数字可以出现多次,我需要找到列表中最不常见的数字。如果不同的数字具有相同的最低频率,则结果是列表中最后出现的数字。例如,[1,7,2,1,2]中最不常见的整数是7(而不是原来所说的2)。而且名单需要保持不分类 我有以下内容,但它总是将最后一个条目设置为leastCommon def least_common_in_unsorted(integers): leastCommon = integers[0] check = 1 appears = 1
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
def least_common_in_unsorted(整数):
leastCommon=整数[0]
检查=1
显示=1
对于整数形式的currentPosition:
如果currentPosition==leastCommon:
显示+1
elif当前位置!=最常见的:
如果检查
编辑:很抱歉,这并不总是按照用户的要求使用最不常见的最后一个列表项……它适用于示例,但并非适用于所有实例。这是我现在想到的最简单的方法:
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
此答案基于@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将保留最后一个具有最小计数的值):
使用:
短而低效:
>>> min(a[::-1], key=a.count)
7
高效版本使用:
[1,7,2,1,2]中的最小公共整数是2“最小公共数是7,对吗?因为它只发生过一次。你说的最小公共数是什么意思Po,对不起,应该是7我已经试过了,谢谢,但这会返回最小公共数的第一个实例,我试图让它返回最后一个实例,如果有两个数字的最低频率相同请参见abccd的回答多次呼叫count
不是很有效,但似乎效果不错。谢谢,我已经尝试了多个不同的列表,效果很好,我正要想出一个像你这样的解决方案。好主意!注意,它比@Arman的答案更简洁,但效率更低。你一直在颠倒相同的列表。
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
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
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
>>> min(a[::-1], key=a.count)
7
>>> min(a[::-1], key=Counter(a).get)
7