【发布时间】:2015-10-06 19:29:56
【问题描述】:
我有一个如下所示的列表:
[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 个 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,它仍然会追加。
【问题讨论】:
-
val 到底是什么?您测试 val 是否不是 None,然后继续向数组中添加其他内容,即“item”。
-
if val is not None怎么不起作用? -
所以我想我有更多信息,val 是来自 api 调用的响应。我认为正在发生的事情是当它没有返回“{u'responseAggregationType': u'byProperty'}”的数据时,然后没有为我正在寻找的其他值插入任何数据。
-
一个好的响应类似于“{u'rows': [{u'keys': [u'8 bit music'], u'impressions': 178.0, u'clicks': 12.0 , u'ctr': 0.06741573033707865, u'position': 3.6179775280898876}], u'responseAggregationType': u'byProperty'}"。
-
所以我尝试做“val = response['rows'],然后如果 val 不是 None:',但我得到一个行 dne 的 keyerror