查找列表中的重复元素 [英] Find duplicate elements in a list
问题描述
我有一个列表:
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
问题:
每次循环时,它都会重新检测元素。因此,有一些元素有许多,而不是被1加1,它由n个幂组成。
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
代码:
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()
推荐答案
计数器是所有你需要的
>>> 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()
运行时:
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
这篇关于查找列表中的重复元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!