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)
我尝试使用的大多数方法也摆脱了中间的空行。任何建议将不胜感激。
这里是一个更有效的方式,但是如果你选择的是不包含在列表中的元素的元素,你可以join和strip与split它只会从正面和背面的元素,保留在中间空的元素。
>>> '-'.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)
查看各种列表方法。您可以使用从左到右的搜索,并检查它们是否是第一个和最后一个元素。相反,只要最左边的元素不受欢迎,只需删除它即可。例如:
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)
这不会检查边缘情况,但会给出总体思路。