简体   繁体   English

从Python清单清单中移除所有

[英]Removing None from Python list of lists

I have a list that looks like this: 我有一个看起来像这样的列表:

[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]

I need to remove the None's so i can iterate through the list. 我需要删除None,以便我可以遍历列表。 Should I not insert if the value is None, or just remove them from the list after they are inserted? 如果值是None,我应该不插入,还是在插入后将它们从列表中删除?

I am building the list like this: 我正在建立这样的列表:

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

The first 5 values are the ones that will return None. 前5个值将返回无。 But looking at the data, sometimes it only inserts 4 None's, sometimes 5. 但是查看数据时,有时只插入4个None,有时插入5个。

I have tried several solutions from stack, such as: 我从堆栈中尝试了几种解决方案,例如:

[x for x in result is not None]

and

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

but for some reason, it will still append even if the val is None. 但是由于某种原因,即使val为None,它仍然会追加。

您缺少列表理解的一部分

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

You need to fix your list comprehension. 您需要修复列表理解。

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