从Python列表中删除None

时间:2015-10-06 19:29:57

标签: python list nonetype

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

[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个值将返回None。但是看一下数据,有时它只会插入4个无,有时是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,它仍会附加。

2 个答案:

答案 0 :(得分:3)

你缺少一份列表理解

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

答案 1 :(得分:2)

您需要修复列表理解。

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')]]