不用collections 输入一个列表,去掉列表中重复的数字,按原来次序输出!
时间: 2024-03-26 08:35:08 浏览: 21
可以通过遍历列表,使用一个空列表作为辅助,将遍历到的数字放入辅助列表中,如果辅助列表中已经存在该数字则跳过,否则将该数字添加到辅助列表中。最后输出辅助列表即可。
以下是示例代码:
```python
def remove_duplicates(lst):
seen = []
result = []
for num in lst:
if num not in seen:
seen.append(num)
result.append(num)
return result
```
使用示例:
```python
>>> lst = [1, 2, 3, 2, 4, 3, 5]
>>> remove_duplicates(lst)
[1, 2, 3, 4, 5]
```
相关问题
输入一个列表,去掉列表中重复的数字,按原来次序输出!
可以使用 Python 的 set() 函数来去重,再使用 list() 函数将 set 转为 list。如下代码:
```
numbers = [1, 2, 3, 2, 1, 4, 5, 6, 5, 6]
numbers = list(set(numbers))
print(numbers)
```
输出:[1, 2, 3, 4, 5, 6]
如果要保留原来的顺序,可以使用collections库里面的OrderedDict,如下代码:
```
from collections import OrderedDict
numbers = [1, 2, 3, 2, 1, 4, 5, 6, 5, 6]
numbers = list(OrderedDict.fromkeys(numbers).keys())
print(numbers)
```
输出:[1, 2, 3, 2, 1, 4, 5, 6, 5, 6]
python 输出一个列表中重复的数据
要输出一个列表中重复的数据,您可以使用Python的collections模块中的Counter类来实现。下面是一个简单的示例代码:
```python
from collections import Counter
def find_duplicates(lst):
counter = Counter(lst)
duplicates = [item for item, count in counter.items() if count > 1]
return duplicates
# 示例列表
lst = [1, 2, 3, 4, 4, 5, 6, 6, 7, 8, 9, 9]
# 输出重复的数据
print(find_duplicates(lst))
```
在上述示例中,我们定义了一个名为`find_duplicates`的函数,该函数使用Counter类来计算列表中每个元素的出现次数。然后,我们通过列表推导式筛选出出现次数大于1的元素,即重复的数据。最后,我们将重复的数据打印出来。
请注意,您可以根据自己的需求进行调整和修改。