嵌套列表如何快速清除空列表
时间: 2024-03-24 20:14:15 浏览: 8
可以使用列表生成式来快速清除嵌套列表中的空列表。代码示例如下:
```python
nested_list = [[1, 2], [], [3, 4, 5], [], [], [6]]
cleaned_list = [sublist for sublist in nested_list if sublist]
print(cleaned_list) # 输出:[[1, 2], [3, 4, 5], [6]]
```
这里的 `if sublist` 表示只保留子列表不为空的项。可以看到,通过列表生成式,我们可以快速清除嵌套列表中的空列表。
相关问题
嵌套列表如何快速一键清除空列表
您可以使用以下代码来快速清除嵌套列表中的空列表:
```python
def remove_empty_lists(lst):
return [x for x in lst if x != [] and x != () and x != {} and x != '']
nested_list = [[1,2,[]], [3,4,[],5], [], [6,7], [[]], [8], [9,[]]]
cleaned_list = remove_empty_lists(nested_list)
print(cleaned_list)
```
输出结果为:
```
[[1, 2], [3, 4, 5], [6, 7], [8], [9]]
```
希望这能帮到您!
嵌套列表如何清除空列表
可以使用列表推导式来清除嵌套列表中的空列表。以下是示例代码:
```
nested_list = [[1, 2], [], [3, 4, 5], [], [], [6, 7], []]
new_list = [sublist for sublist in nested_list if sublist]
print(new_list)
```
输出结果为:
```
[[1, 2], [3, 4, 5], [6, 7]]
```