在列表中查找重复元素

时间:2014-03-16 20:08:04

标签: python python-3.x duplicates

我有一个清单:

nums = [1, 2, 3, 1, 5, 2, 7, 11]

我正在尝试创建一个函数,返回每个数字在列表中出现的次数。输出可能如下所示:

1 occurred 2 times
2 occurred 2 times
3 occurred 1 time
5 occurred 1 time
...
...

这是我到目前为止所尝试的:
- 为列表中的每个元素创建字典
- 有嵌套循环遍历每个元素并检查每个其他元素
- 如果元素匹配,则在该元素的字典键中添加一个

问题:
每次循环时,它都会重新检测相同的元素。因此,无论某个元素有多少,而不是加1,它都会被n幂提升

Enter integers between 1 and 100: 5 2 41 4 5 2 2 4
4 occurs 4 times
2 occurs 9 times
41 occurs 1 times
5 occurs 4 times

代码:

def main():
    original_nums = input("Enter integers between 1 and 100: ")
    nums = [i for i in original_nums.split()]
    my_dict = {}

    for i in nums:
        my_dict[i] = 0

    for i in nums:
        for j in nums:
            if i == j:
                my_dict[i] += 1

    for i in my_dict:
        print(i,"occurs",my_dict[i],"times")



if __name__ == "__main__":
    main()

2 个答案:

答案 0 :(得分:8)

Counter就是您所需要的一切

>>> from collections import Counter
>>> Counter([1, 2, 3, 1, 5, 2, 7, 11])
Counter({1: 2, 2: 2, 3: 1, 5: 1, 7: 1, 11: 1})

您可以像这样修复您的代码

def main():
    original_nums = input("Enter integers between 1 and 100: ")
    nums = [i for i in original_nums.split()]
    my_dict = {}

    for i in nums:
        my_dict[i] = my_dict.get(i, 0) + 1
        # or .setdefault(i, 0) instead of .get(i, 0)
        # setdefault is generally faster

    for i in my_dict:
        print(i, 'occurs', my_dict[i], 'times')

if __name__ == '__main__':
    main()

运行时:

Enter integers between 1 and 100: 5 5 5 5 1 2 3 3 3 
1 occurs 1 times
2 occurs 1 times
3 occurs 3 times
5 occurs 4 times

答案 1 :(得分:3)

你可以简单地使用collections.Counter,它基本上是你在内部尝试做的事情:

>>> from collections import Counter
>>> 
>>> nums = [1, 2, 3, 1, 5, 2, 7, 11]
>>> 
>>> counts = Counter(nums)
>>> 
>>> for t in counts.iteritems():
...     print '%d occured %d times' % t
... 
1 occured 2 times
2 occured 2 times
3 occured 1 times
5 occured 1 times
7 occured 1 times
11 occured 1 times