py找出数组中重复的数字
时间: 2024-09-12 09:04:49 浏览: 43
要在Python中找出数组中重复的数字,可以使用多种方法。以下是一种常见的方法,使用字典来记录每个元素出现的次数,然后根据条件筛选出重复的数字:
```python
def find_duplicates(nums):
num_dict = {}
duplicates = []
for num in nums:
num_dict[num] = num_dict.get(num, 0) + 1
for key, value in num_dict.items():
if value > 1:
duplicates.append(key)
return duplicates
# 示例数组
nums = [1, 2, 3, 2, 3, 4, 5, 4]
# 调用函数
print(find_duplicates(nums))
```
在上面的代码中,`find_duplicates` 函数首先遍历数组 `nums`,使用字典 `num_dict` 来统计每个数字出现的次数。遍历完成后,再次遍历字典,将那些出现次数大于1的数字添加到 `duplicates` 列表中。最后返回包含所有重复数字的列表。
阅读全文
相关推荐

















