python list套list如何去重
时间: 2023-11-22 15:47:17 浏览: 80
python列表list保留顺序去重的实例
5星 · 资源好评率100%
可以使用列表推导式和set()函数来去重python list套list。具体方法如下:
1. 列表推导式:使用两层循环,外层循环遍历每个子列表,内层循环遍历子列表中的元素,将不重复的元素添加到新列表中。
2. set()函数:将所有子列表转换为集合,再将集合转换为列表,即可去重。
代码示例:
1. 列表推导式
```
lst = [[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6], [5, 6, 7], [6, 7, 8], [7, 8, 9], [8, 9, 10], [9, 10, 11], [10, 11, 12], [11, 12, 13], [12, 13, 14], [13, 14, 15], [14, 15, 16], [15, 16, 17], [16, 17, 18], [17, 18, 19], [18, 19, 20], [19, 20, 21], [20, 21, 22]]
new_lst = []
[new_lst.append(sub_lst) for sub_lst in lst if sub_lst not in new_lst]
print(new_lst)
```
2. set()函数
```
lst = [[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6], [5, 6, 7], [6, 7, 8], [7, 8, 9], [8, 9, 10], [9, 10, 11], [10, 11, 12], [11, 12, 13], [12, 13, 14], [13, 14, 15], [14, 15, 16], [15, 16, 17], [16, 17, 18], [17, 18, 19], [18, 19, 20], [19, 20, 21], [20, 21, 22]]
new_lst = list(set(tuple(sub_lst) for sub_lst in lst))
new_lst = [list(sub_lst) for sub_lst in new_lst]
print(new_lst)
```
阅读全文