python怎么去掉为空的list元素
时间: 2023-10-19 18:07:54 浏览: 48
可以使用列表推导式或者filter函数来去掉为空的list元素。
方法一:使用列表推导式
```python
list1 = [1, 2, 3, '', 5, '', 7, 8, '']
list1 = [x for x in list1 if x]
print(list1)
```
输出:
```
[1, 2, 3, 5, 7, 8]
```
方法二:使用filter函数
```python
list1 = [1, 2, 3, '', 5, '', 7, 8, '']
list1 = list(filter(None, list1))
print(list1)
```
输出:
```
[1, 2, 3, 5, 7, 8]
```
方法三:使用remove函数
```python
list1 = [1, 2, 3, '', 5, '', 7, 8, '']
for item in list1:
if item == '':
list1.remove(item)
print(list1)
```
输出:
```
[1, 2, 3, 5, 7, 8]
```
需要注意的是,在迭代列表时不能直接删除元素,否则会导致索引错乱,可以使用for循环和remove函数来实现。
相关问题
python去除列表空元素
可以使用列表推导式来去除列表中的空元素,代码如下:
```python
my_list = ["hello", "", "world", "", " "]
new_list = [x for x in my_list if x.strip()]
print(new_list)
```
输出结果为:
```
['hello', 'world']
```
该代码使用 `strip()` 函数去除每个元素两端的空格,然后判断是否为空字符串,如果不为空,则将该元素添加到新列表中。
python的lsit怎么去掉为空的tensor元素
假设你的列表名为`my_list`,其中包含了一些Tensor元素。你可以使用以下代码去除其中为空的Tensor元素:
```python
import torch
my_list = [torch.Tensor([1, 2]), torch.Tensor([]), torch.Tensor([3, 4]), torch.Tensor([])]
my_list = [x for x in my_list if x.numel() > 0]
print(my_list)
```
输出:
```
[tensor([1., 2.]), tensor([3., 4.])]
```
在这里,我们使用了`numel()`函数,该函数返回Tensor中的元素数量。如果Tensor的元素数量大于0,则保留该Tensor元素。否则,将该Tensor元素从列表中删除。