删除列表中的空格字符

时间:2018-12-28 06:42:26

标签: python list

如何删除该列表中的空格('')?

list = ['a', 'b', 'c', ' ', '1', '2', '3', ' ', 'd', 'e','f']

据我所知,pop / remove方法适用于切片,但是空格字符根据输入而改变位置。

4 个答案:

答案 0 :(得分:4)

有条件的comprehension可以做到:

lst = ['a', 'b', 'c', ' ', '1', '2', '3', ' ', 'd', 'e','f']  # do not shadow 'list'

lst = [x for x in lst if x != ' ']

如果您必须更改现有的list对象而不仅仅是重新绑定变量,请使用切片分配

lst[:] = [x for x in lst if x != ' ']

如果要删除仅由空格字符组成的任何字符串,可以使用str.strip()

lst = [x for x in lst if x.strip()]

请注意,从性能上重新构建列表通常比重复调用delpopremove更好,因为每个调用都具有线性复杂度,因为删除索引需要在基础数组中移动。

答案 1 :(得分:1)

您可以使用del函数从列表中删除该元素。

代码:

lst = ['a', 'b', 'c', ' ', '1', '2', '3', ' ', 'd', 'e','f']
count = 0
for i in lst:
    if i == ' ':
        del lst[count]
    count = count + 1
print(lst)

输出:

['a', 'b', 'c', '1', '2', '3', 'd', 'e', 'f'] 

答案 2 :(得分:0)

下面是实现您想要的功能的方法:

list_input = ['a', 'b', 'c', ' ', '1', '2', '3', ' ', 'd', 'e','f']
print(list(filter(lambda elem: elem != ' ', list_input)))

# Output: ['a', 'b', 'c', '1', '2', '3', 'd', 'e', 'f']             

更多的pythonic列表理解方法:

list_input = ['a', 'b', 'c', ' ', '1', '2', '3', ' ', 'd', 'e','f']
print([elem for elem in list_input if elem != ' '])         

# Output: ['a', 'b', 'c', '1', '2', '3', 'd', 'e', 'f']  

答案 3 :(得分:0)

只需记住itertools

from itertools import filterfalse

list(filterfalse(lambda x: x == ' ', lst))
#=> ['a', 'b', 'c', '1', '2', '3', 'd', 'e', 'f']