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

时间:2017-07-24 00:43:58

标签: python list count python-2.x

问题实际上是这样的 编写一个程序,说明要替换的术语数,以使列表中的所有数字相同 前 A = [1,1,2,1,1,4,1,1] 然后预期的输出是2

3 个答案:

答案 0 :(得分:0)

您可以遍历列表并制作事件字典:

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())))

现在你可以对事件进行判断,你可以这样做以获得要替换的术语数量:

onActionModeStarted

这将为您提供最少的更改次数。通过这种方式,您无法指定希望整个列表包含哪个元素

答案 1 :(得分:0)

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

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])

答案 2 :(得分:0)

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

# 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])