两个list集合对象去重
时间: 2023-12-09 13:35:14 浏览: 112
两个数组去重的JS代码
以下是两个List集合对象去重的方法:
1.使用Set集合去重
```python
list1 = [1, 2, 3, 4, 5]
list2 = [4, 5, 6, 7, 8]
set1 = set(list1)
set2 = set(list2)
result = list(set1.union(set2))
print(result) # 输出:[1, 2, 3, 4, 5, 6, 7, 8]
```
2.使用列表推导式去重
```python
list1 = [1, 2, 3, 4, 5]
list2 = [4, 5, 6, 7, 8]
result = list(set([i for i in list1] + [j for j in list2]))
print(result) # 输出:[1, 2, 3, 4, 5, 6, 7, 8]
```
3.使用循环去重
```python
list1 = [1, 2, 3, 4, 5]
list2 = [4, 5, 6, 7, 8]
result = list1.copy()
for i in list2:
if i not in result:
result.append(i)
print(result) # 输出:[1, 2, 3, 4, 5, 6, 7, 8]
```
阅读全文