计算 python 列表中未重复的术语数

counting the number of terms that are not repeated in the python list

问题实际上是这样的 编写一个程序,说出要替换的项数以获得列表中所有相同的数字 前任 一=[1,1,2,1,1,4,1,1] 那么预期的输出是 2

您可以遍历列表并制作出现的字典:

occurrences = {}
for x in range(len(a)):
   if a[x] not in occurences:
      occurrences[x] = 1
   else:
      occurrences[x] += 1

现在你可以得到出现次数的字典,你可以这样做来获得要替换的术语数:

nums = list(occurrences.values()).sort(reverse=True) # Sort I descending order with num of repetitions
print(sum(nums[1:])) # Add occurrences of all but the element with max occurrences

#Or just subtract the max occurrence from the length of list

print(len(a) - max(list(occurrences.values())))

这将使您需要进行的更改最少。这样你就不能指定你希望整个列表包含哪个元素

你的措辞有点奇怪。 如果你想要不是一个的项目数:

len([i for i in a if i!=1])

len(a)-a.count(1)

如果你想要唯一的一组不重复的数字,如问题所述:

len([i for i in set(a) if a.count(i)==1])

我猜你正在寻找要替换的最小数字数,以便所有数字都相同。

# store occurrences of each number in a dictionary
d = {}
for i in a:
    if i not in d:
        d[i] = 1
    else:
        d[i] += 1

 # get key with max value: i.e. most frequent number in initial list
 max_k = max(d, key=d.get)

 # delete element that appears most often in the initial list
 del d[max_k]

 # count rest of the numbers => numbers to be replaced
 nums_to_replaces = sum([d[k] for k in d])