【问题标题】:Removing None from Python list of lists从 Python 列表中删除 None
【发布时间】: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

标签: python list nonetype


【解决方案1】:

你错过了你的列表理解的一部分

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

【讨论】:

  • if val is not None: 应该有效,所以问题必须更多
  • @PadraicCunningham 这个问题还有什么意义。我用他的确切清单试了一下,它奏效了。也许val 与我们认为的val1val2 无关,或者array 不是开始为空。
  • 是的,抱歉,val 与其他 val 无关
  • @cmd,如果 OP 没有添加 Nones ,则根本不需要过滤,他们创建了列表,因此应该可以不首先添加它们,因此我说 @987654327如果 val 是他们添加的内容,@ 应该可以工作
  • @PadraicCunningham 是的,但由于不包括添加None 的代码...
【解决方案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')]]

【讨论】:

  • ty,我做到了这一点,并且能够将结果传递给 itertools 并将其转换为 mysql mass insert 的列表列表。
猜你喜欢
  • 2013-04-12
  • 1970-01-01
  • 1970-01-01
  • 2022-10-25
  • 2020-01-23
  • 1970-01-01
  • 2017-11-02
  • 2021-02-13
  • 1970-01-01
相关资源
最近更新 更多