繁体   English   中英

从Python清单清单中移除所有

[英]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个值将返回无。 但是查看数据时,有时只插入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')]]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM