python代码统计元素重复出现并删除同样的元素
时间: 2024-12-13 12:24:53 浏览: 12
在Python中,你可以使用字典(dict)或者集合(set)来统计列表中元素的重复次数,并通过去重操作移除重复元素。这里分别给出两种方法:
1. **使用字典**(基于键值对计数,不保持原始顺序,适用于无序数据):
```python
def count_and_remove_duplicates(lst):
unique_dict = {}
result = []
for item in lst:
if item not in unique_dict:
unique_dict[item] = 0
unique_dict[item] += 1
return [item for item, count in unique_dict.items() if count == 1]
# 示例
lst = [1, 2, 2, 3, 4, 4, 5]
new_lst = count_and_remove_duplicates(lst)
print(new_lst) # 输出:[1, 3, 5]
```
2. **使用集合**(保留唯一元素,丢失原始顺序,适用于无序且不需要保持原有频率的数据):
```python
def remove_duplicates(lst):
return list(set(lst))
# 示例
lst = [1, 2, 2, 3, 4, 4, 5]
new_lst = remove_duplicates(lst)
print(new_lst) # 输出:[1, 2, 3, 4, 5]
```
如果你想保持原始顺序,可以使用 `collections.Counter` 和 `dict.fromkeys()` 结合:
```python
from collections import Counter
def count_and_remove_duplicates_ordered(lst):
counter = Counter(lst)
return list(dict.fromkeys(counter.keys()))
# 示例
lst = [1, 2, 2, 3, 4, 4, 5]
new_lst = count_and_remove_duplicates_ordered(lst)
print(new_lst) # 输出:[1, 2, 3, 4, 5]
```
阅读全文