去除列表的列表中的空列表的Python代码
时间: 2023-10-30 20:34:13 浏览: 37
可以使用列表推导式来实现去除列表的列表中的空列表,示例代码如下:
```
nested_list = [[1, 2, 3], [], [4, 5], [], [], [6, 7, 8, 9], []]
new_list = [x for x in nested_list if x != []]
print(new_list)
```
输出结果为:
```
[[1, 2, 3], [4, 5], [6, 7, 8, 9]]
```
在上述代码中,我们使用了列表推导式来创建一个新的列表,该列表包含原始列表中不为空的子列表。在列表推导式中,我们使用了一个 if 条件语句,该条件语句判断子列表是否为空,如果不为空则将其添加到新列表中。
相关问题
python去除列表中的空字符串
您好,针对您的问题,可以使用Python的列表推导式来去除列表中的空字符串。具体代码如下:
```
original_list = ["hello", "", "world", "", " ", "AI", " "]
new_list = [word for word in original_list if word.strip()]
print(new_list)
```
运行结果为:
```
['hello', 'world', 'AI']
```
这样就将原始列表中的空字符串以及只包含空格的字符串都去除了。
python怎么去除列表中的空字符串
可以使用列表推导式和条件判断来去除列表中的空字符串。具体代码如下:
```python
my_list = ["", "Hello", "", "World", "", ""]
new_list = [x for x in my_list if x != ""]
print(new_list)
```
输出结果为:
```python
['Hello', 'World']
```
在这个代码中,我们首先定义了一个包含空字符串的列表 `my_list`。然后,我们使用列表推导式和条件判断来创建一个新的列表 `new_list`,其中只包含不是空字符串的元素。最后,我们打印出新的列表 `new_list`,其结果不包含空字符串。