这是我想要放入另一个列表中替换所有零值的数字列表
a = [2, 5, 6, 3, 9]
这是替换所有零值之前另一个列表的样子
b = [0, 7, 9, 3, 3, 0, 4, 0, 3, 1, 0, 0, 4]
what I'm trying to achieve is to copy the first list in to the second list so it replaces all the zero values like so
c = [2, 7, 9, 3, 3, 5, 4, 6, 3, 1, 3, 9, 4]
If there are too many zeroes in b
, it will just be ignored and will stay 0 in c
and if the there are too few zeroes in b
, some values in a would simply not be carried over or copied to c
edit
and is there a way to do this to fill a list like this
b = [[0, 3, 9, 1, 3]
[3, 3, 4, 2, 0]
[3, 5, 5, 0, 2]
[0, 0, 3, 8, 9]
[1, 2, 3, 4, 5]]
这样 c
将是
c = [[2, 3, 9, 1, 3]
[3, 3, 4, 2, 5]
[3, 5, 5, 6, 2]
[3, 9, 3, 8, 9]
[1, 2, 3, 4, 5]]
最佳答案
一种方法是使用 iter
创建一个对象,将 a
中的每个元素一一给出,然后使用普通的 listcomp:
>>> a = [2, 5, 6, 3, 9]
>>> b = [0, 7, 9, 3, 3, 0, 4, 0, 3, 1, 0, 0, 4]
>>> fill = iter(a)
>>> c = [x if x != 0 else next(fill) for x in b]
>>> c
[2, 7, 9, 3, 3, 5, 4, 6, 3, 1, 3, 9, 4]
正如 @bulbus 所指出的,如果没有足够的零来填充,这将引发 StopIteration 异常。您可以使用 next
的默认值,例如next(fill, 0)
如果你想避免这种情况。
对于您的 2D 情况,相同的方法有效,我们只需要更改 listcomp:
>>> fill = iter(a)
>>> b = [[0, 3, 9, 1, 3], [3, 3, 4, 2, 0], [3, 5, 5, 0, 2], [0, 0, 3, 8, 9], [1, 2, 3, 4, 5]]
>>> c = [[x if x != 0 else next(fill) for x in row] for row in b]
>>> c
[[2, 3, 9, 1, 3], [3, 3, 4, 2, 5], [3, 5, 5, 6, 2], [3, 9, 3, 8, 9], [1, 2, 3, 4, 5]]
关于复制非零值列表以填充另一个列表的零的 Pythonic 方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46391560/