如何删除列表Python开头和结尾的空白元素

p s*_*eth 2 python string list

我有一个字符串列表,只需要删除列表开头和结尾的空字符串序列。我需要保留非空字符串之间的任何空字符串。

例如,

my_list = ['', '', 'Sam sits', '', 'Thinking of you.', '', 'All ideas bad.', '', '', '']  
Run Code Online (Sandbox Code Playgroud)

输出应该是;

['Sam sits', '', 'Thinking of you.', '', 'All ideas bad.']  
Run Code Online (Sandbox Code Playgroud)

我尝试使用的大多数方法也摆脱了中间的空行。任何建议将不胜感激。

use*_*203 6

这里一个更有效的方式,但是如果你选择的是不包含在列表中的元素的元素,你可以joinstripsplit它只会从正面和背面的元素,保留在中间空的元素。

>>> '-'.join(my_list).strip('-').split('-')
['Sam sits', '', 'Thinking of you.', '', 'All ideas bad.']
Run Code Online (Sandbox Code Playgroud)

扩展此方法以将列表中间较长的空字符串连接到单个空字符串:

import re

def remove_join(arr, el):
    return re.split(r'\{}+()'.format(el), el.join(arr).strip(el))

>>> my_list = ['', '', 'test', '', '', '', 'test2', '', '']
>>> remove_join(my_list, '-')
['test', '', 'test2']
Run Code Online (Sandbox Code Playgroud)

  • 如果您不能提前指定不在字符串中的字符怎么办?我猜你可以使用 `'\0'`,因为它不太可能用在普通的文本字符串中。否则,您需要先扫描所有字符串以选择未使用的字符。 (2认同)

Pru*_*une 5

查看各种列表方法。您可以使用从左到右的搜索,并检查它们是否是第一个和最后一个元素。相反,只要最左边的元素不受欢迎,只需删除它即可。例如:

while my_list[0] == '':
    my_list.pop(0)

while my_list[-1] == '':
    my_list.pop(-1)
Run Code Online (Sandbox Code Playgroud)

为了提高效率(创建一个新列表,但只更改一个列表):

# First, form a Boolean list that identifies non-empty elements
has_content = [len(s) > 0 for s in my_list]
# Then find the left and right non-empty elements.
left  = has_content.find(True)    # find the left  non-empty string
right = has_content.rfind(True)   # find the right non-empty string
new_list = my_list[left:right+1]
Run Code Online (Sandbox Code Playgroud)

这不会检查边缘情况,但会给出总体思路。