迭代并通过双数组替换

时间:2013-10-09 20:04:23

标签: python

拥有这个数组:

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

我需要将0的值替换为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]

3 个答案:

答案 0 :(得分: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]]

答案 1 :(得分: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]]

答案 2 :(得分: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]]
>>>