从列表的 Python 列表中删除 None

Removing None from Python list of lists

我有一个如下所示的列表:

[None, None, None, None, [(u'data1', 2.0, 2.0, 1.0, 1.0, '2015-10-01', '2015-10-01')], None, None, None, None, [(u'data2', 8.0, 5.0, 0.625, 1.25, '2015-10-01', '2015-10-01')], None, None, None, None, None, None, [(u'data3', 1.0, 1.0, 1.0, 1.0, '2015-10-01', '2015-10-01')], None, None, None, None, None, None, None, None, None, None, None, None, None]

我需要删除 None 以便遍历列表。如果值为 None,我应该不插入,还是在插入后将它们从列表中删除?

我正在构建这样的列表:

item = (val1, val2, val3, val4, val5, start_date, end_date)
array.append(item)

前 5 个值将 return None。但是看数据,有时候只插入4个None,有时候是5个

我尝试了几种堆栈解决方案,例如:

[x for x in result is not None]

if val is not None:
    item = (val1, val2, val3, val4, val5, start_date, end_date)
    array.append(item)

但出于某种原因,即使 val 为 None,它仍会追加。

您缺少对列表理解的一部分

[x for x in result if x is not None]

你需要修正你的列表理解。

results = [None, None, None, None, [(u'data1', 2.0, 2.0, 1.0, 1.0, '2015-10-01', '2015-10-01')], None, None, None, None, [(u'data2', 8.0, 5.0, 0.625, 1.25, '2015-10-01', '2015-10-01')], None, None, None, None, None, None, [(u'data3', 1.0, 1.0, 1.0, 1.0, '2015-10-01', '2015-10-01')], None, None, None, None, None, None, None, None, None, None, None, None, None]
results = [result for result in results if result is not None]
>>> [[(u'data1', 2.0, 2.0, 1.0, 1.0, '2015-10-01', '2015-10-01')], [(u'data2', 8.0, 5.0, 0.625, 1.25, '2015-10-01', '2015-10-01')], [(u'data3', 1.0, 1.0, 1.0, 1.0, '2015-10-01', '2015-10-01')]]