我有样式列表:

[None, ..., None, "c", 1, 3, None, None, 4.3, "b", None, "4", None, ..., None]

我想有效地缩短为:

["c", 1, 3, None, None, 4.3, "b", None, "4"]

直截了当,我可以做到:

def _shorten(long_list):
  start = False
  short_list = []
  for e in long_list:
    if e:
      start = True
    if start:
      short_list.append(e)
  return short_list

reversed(_shorten(reversed(_shorten(long_list))))

推荐答案

try :

lst = [None, None, None, None]

i = 0
while i < len(lst) - 1 and lst[i] is None:
    i += 1

j = len(lst) - 1
while j > 0 and lst[j] is None:
    j -= 1

print(lst[i : j + 1])

编辑:删除了第一个O(n^2)答案

Python-3.x相关问答推荐

是否有必要使用Threads()中的args显式地将共享变量传递给Python中的线程函数或直接访问它?

被多个\n拆分并保留

泛型类型的参数的静态类型

数据框中从每个组/ID的底部删除行

如何在类中的函数(以 self 作为第一个参数)中使用递归

Python base64.b32hexencode 未创建预期结果

如何使用复选按钮更改 Pyplot 轴的属性?

使用gekko python的混合整数非线性规划

如何通过从特定列创建分组多标题来reshape 数据框?

双轴上的刻度和标签

正则表达式来识别用 Python 写成单词的数字?

Python:如何从句子/段落中提取地址(非正则表达式方法)?

集合操作:应该只适用于集合,但适用于 dict_keys?

运行 pip install -r requirements.txt 时出错

Python - 使用 OpenCV 将字节图像转换为 NumPy 数组

Pytorch 的随机 Select ?

为 True 相交两个布尔数组

根据条件过滤元组列表

print(... sep='', '\t' ) 是什么意思?

如何使用 Celery 和 Django 将任务路由到不同的队列