有了一个数字列表,每个数字可以出现多次,我需要找到列表中最不常见的数字。如果不同的数字具有相同的最低频率,则结果是列表中最后出现的数字。例如,[1,7,2,1,2]中最不常用的整数是7(不是2,正如最初所说)。名单需要不排序
我有以下内容,但它总是将最后一个条目设置为leastCommon
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
关于python - 在列表python中标识最小公数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47098026/