计算列表中重复项的数量 [英] Counting the number of duplicates in a list

查看:138
本文介绍了计算列表中重复项的数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试构造此函数,但无法解决如何停止重复计数同一重复项的功能.有人可以帮我吗?

I am trying to construct this function but I can't work out how to stop the function counting the same duplicate more than once. Can someone help me please?

def count_duplicates(seq): 

    '''takes as argument a sequence and
    returns the number of duplicate elements'''

    fir = 0
    sec = 1
    count = 0
    while fir < len(seq):
        while sec < len(seq):
            if seq[fir] == seq[sec]:
                count = count + 1
            sec = sec + 1
        fir = fir + 1
        sec = fir + 1
    return count 

在:count_duplicates([-1,2,4,2,0,4,4])

出局:4

此处失败,因为输出应为3.

It fails here because the output should be 3.

推荐答案

您可以从列表中创建一个set,该列表将自动删除重复项,然后计算所创建的集合与原始列表的长度之差. 像这样:

You can just create a set from your list that would automatically remove the duplicates and then calculate the difference of the lengths of the created set and the original list. Like so:

def count_duplicates(seq): 

    '''takes as argument a sequence and
    returns the number of duplicate elements'''

    return len(seq) - len(set(seq))

res = count_duplicates([-1,2,4,2,0,4,4])
print(res)  # -> 3

如果不允许或不想使用任何内置的快捷方式(无论出于何种原因),您可以花很长的时间:

If you are not allowed or don't want to use any built-in shortcuts (for whatever reason), you can take the long(er) way around:

def count_duplicates2(seq): 

    '''takes as argument a sequence and
    returns the number of duplicate elements'''

    counter = 0
    seen = set()
    for elm in seq:
        if elm in seen:
            counter += 1
        else:
            seen.add(elm)
    return counter

res = count_duplicates2([-1,2,4,2,0,4,4])
print(res)  # -> 3


最后,就您的代码而言,@AlanB在他的答案中很好地概述了与代码有关的问题>.我选择不麻烦更正您的代码,因为在我看来这是一个 XY问题.显然,您具有某种编程背景,但是复杂的while循环只是而不是在Python中完成事情的方式.


Finally, as far as your code is concerned, the problems with it are outlined very nicely by @AlanB in his answer. I chose not to bother correcting your code because in my mind this is an XY Problem. It is obvious that you have some kind of programming background but your convoluted while loops is just not the way things are done in Python.

这篇关于计算列表中重复项的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆