用Python写:输入一个列表,去掉列表中重复的数字,按原来次序输出
时间: 2023-05-20 17:01:01 浏览: 74
可以使用以下代码实现:
```python
def remove_duplicates(lst):
seen = set()
result = []
for item in lst:
if item not in seen:
seen.add(item)
result.append(item)
return result
lst = [1, 2, 3, 2, 1, 4, 5, 4, 6]
print(remove_duplicates(lst)) # 输出 [1, 2, 3, 4, 5, 6]
```
这个函数接受一个列表作为参数,使用一个集合来记录已经出现过的数字,然后遍历列表,如果当前数字没有出现过,就将它加入集合和结果列表中。最后返回结果列表即可。
相关问题
python输入一个列表,去掉列表中重复的数字,按原来次序输出!
请问你想得到的输入和输出是什么?
如果你想输入一个列表,然后去掉列表中重复的数字,按原来的顺序输出,可以按如下方式实现:
1. 使用 set 去掉列表中的重复数字
2. 将去重后的 set 转换为列表
3. 按原来的顺序输出列表
下面是示例代码:
```python
# 输入一个列表
lst = [1, 2, 3, 2, 1, 4]
# 去掉重复数字,并转换为列表
lst_no_duplicate = list(set(lst))
# 按原来的顺序输出
for i in lst:
if i in lst_no_duplicate:
print(i)
lst_no_duplicate.remove(i)
```
上面的代码输出的结果是:
```
1
2
3
4
```
希望对你有所帮助!
Python输入一个列表,去掉列表中重复的数字,按原来次序输出
好的,可以使用以下代码实现:
```python
def remove_duplicates(lst):
new_lst = []
for item in lst:
if item not in new_lst:
new_lst.append(item)
return new_lst
lst = [1, 2, 3, 4, 3, 2, 1]
new_lst = remove_duplicates(lst)
print(new_lst)
```
输出结果为:`[1, 2, 3, 4]`。
这里定义了一个 `remove_duplicates` 函数,接受一个列表作为参数。使用一个新的空列表 `new_lst`,遍历原始列表 `lst` 中的每一个元素,如果该元素不在新列表中,就将它添加到新列表中。最后返回新列表。
这样就可以去掉列表中的重复元素,并保持原来的次序不变。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![py](https://img-home.csdnimg.cn/images/20210720083646.png)