简体   繁体   中英

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. Should I not insert if the value is None, or just remove them from the list after they are inserted?

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. But looking at the data, sometimes it only inserts 4 None's, sometimes 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.

您缺少列表理解的一部分

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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