1

有这个数组:

a = [1, None, 2], [3, 4, 5], [6, None, 7]

我需要将 None 的值替换为 0。我的第一个实现是遍历数组,但我想在一行中完成。

我尝试了这样的事情,但没有奏效:

a = [0 if value is None else value for value in a[i][1] for i in range(len(a))]

显然不起作用,正确的方法是什么?

编辑:我不想触摸其他位置,只是数组中每个元素的第二个位置。

这个:

a = [None, None, 2], [3, 4, 5], [6, None, 7]

将返回:

a = [None, 0, 2], [3, 4, 5], [6, 0, 7]
4

3 回答 3

3

使用or

>>> a = [[1, None, 2], [3, 4, 5], [6, None, 7]]
>>> [[x or 0 for x in l] for l in a]
[[1, 0, 2], [3, 4, 5], [6, 0, 7]]

或者,如果您只想评估第二个元素:

>>> a = [[1, None, 2], [3, 4, 5], [6, None, 7]]
>>> [[l[0], l[1] or 0] + l[2:] for l in a]
[[1, 0, 2], [3, 4, 5], [6, 0, 7]]
于 2013-10-09T20:07:59.483 回答
2

使用嵌套列表推导:

>>> a = [[1, None, 2], [3, 4, 5], [6, None, 7]]
>>> [[0 if x is None else x for x in sublist] for sublist in a]
[[1, 0, 2], [3, 4, 5], [6, 0, 7]]

或者另一种方法,您只查看每个子列表中的第二项:

>>> [x[:1] + ([0] if x[1] is None else x[1:2]) + x[2:] for x in a]
[[1, 0, 2], [3, 4, 5], [6, 0, 7]]
于 2013-10-09T20:06:40.933 回答
1

嵌套列表推导会做到这一点:

>>> a = [1, None, 2], [3, 4, 5], [6, None, 7]
>>> [[c if c is not None else 0 for c in b] for b in a]
[[1, 0, 2], [3, 4, 5], [6, 0, 7]]
>>>
于 2013-10-09T20:06:48.780 回答