使用Python代码实现列表去重li1=[1,2,3,3,3,1,4,2,4,4,5,6,8,6,8,7,8],通过两种方式实现
时间: 2023-10-03 20:05:56 浏览: 80
方法一:通过set函数去重
```python
li1 = [1,2,3,3,3,1,4,2,4,4,5,6,8,6,8,7,8]
li2 = list(set(li1))
print(li2)
```
输出:
```
[1, 2, 3, 4, 5, 6, 7, 8]
```
方法二:通过循环遍历去重
```python
li1 = [1,2,3,3,3,1,4,2,4,4,5,6,8,6,8,7,8]
li2 = []
for i in li1:
if i not in li2:
li2.append(i)
print(li2)
```
输出:
```
[1, 2, 3, 4, 5, 6, 8, 7]
```
相关问题
已知列表li_one = [1,2,1,2,3,5,4,3,5,7,4,7,8],编写python程序实现删除列表li_one中重复数据
可以使用set()函数将列表转化为集合,此时集合会自动去重,然后再将集合转化为列表即可。
代码如下:
li_one = [1,2,1,2,3,5,4,3,5,7,4,7,8]
li_one = list(set(li_one))
print(li_one)
输出结果为:
[1, 2, 3, 4, 5, 7, 8]
使用python语言完成如下问题并给出代码:5.已知列表li_one=[1,2,1,2,3,5,4,3,5,7,4,7,8],删除列表中重复数据
方法一:使用set()函数去重,再转换回list类型
```python
li_one = [1,2,1,2,3,5,4,3,5,7,4,7,8]
li_one = list(set(li_one))
print(li_one)
```
方法二:遍历列表,把第一次出现的元素添加到新列表中,遇到重复元素跳过
```python
li_one = [1,2,1,2,3,5,4,3,5,7,4,7,8]
li_two = []
for i in li_one:
if i not in li_two:
li_two.append(i)
print(li_two)
```
输出结果:
```
[1, 2, 3, 4, 5, 7, 8]
```
阅读全文