python - 删除列表的元素,直到到达 Python 中的第一个空元素
问题描述
我有这个字符串列表
list = ['1', '2', '3', '4', '', ' 5', ' ', ' 6', '', '']
我想在第一个空字符串之后获取每个项目以获得此结果
list = [' 5', ' ', ' 6', '', '']
请注意,我想留下后面的空字符串
我写了这个函数:
def get_message_text(list):
for i, item in enumerate(list):
del list[i]
if item == '':
break
return list
但我无缘无故地得到这个错误的结果:
['2', '4', ' 5', ' ', ' 6', '', '']
有什么帮助吗?
解决方案
只需找到第一个空字符串的索引并对其进行切片:
def get_message_text(lst):
try:
return lst[lst.index("") + 1:]
except ValueError: # '' is not in list
return [] # if there's no empty string then don't return anything
推荐阅读
- javascript - 使用颜色选择器值在图像 url 中打印颜色?
- nginx - Nginx - 在缓存过期时使用 proxy_cache_lock 逻辑以避免多上行请求
- vb.net - 如何在 Visual Basic 中从 Ms Access 数据库中获取特定列
- elasticsearch - 在 Elasticsearch 中使用搜索模板进行日期范围查询
- typescript - 如何访问基类对象以列出其属性?
- python - 从数组列表Python中获取平均列值
- excel - vba图表X轴
- html - 如何将一条线的 SVG 路径旋转 90 度
- c# - 如何在 C# 中使用 JSON 使用构造函数填充对象属性?
- css - 用渐变绘制气泡反射