Find duplicate elements in a list

天涯浪子 提交于 2020-01-05 15:04:12

问题


I have a lists:

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

I am trying to make a function that returns how many times each number appears in the lists. Output may look like:

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

This is what I have tried so far:
-Create dictionary for each element in list
-Have nested loop go through every element and check it against every other element
-If elements match add one to the dictionary key of that element

The problem:
Everytime it loops through, it redetects the same elements. Therefore however many of a certain element there is, instead of being added by 1, it is raised by the n power

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

code:

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

回答1:


Counter is all you need

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

Or you can just fix your code like this

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

Runtime:

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



回答2:


You can simply use a collections.Counter, which essentially does what you're trying to do internally:

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


来源:https://stackoverflow.com/questions/22442273/find-duplicate-elements-in-a-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!