复制非零值列表以填充另一个列表的零的 Pythonic 方式

标签 python list

这是我想要放入另一个列表中替换所有零值的数字列表

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/

相关文章:

python - 一行功能统计彩票中奖券

python - 在元组列表中按字母对数字求和

python - 当我将 PyQt4 中的 QWebView 放入函数中时,它不会打开

python - 尝试从 pyevolve 导入时出现 "AttributeError: fileno"

c - 列表不退出循环?

Python 在使用 zip() 遍历列表时不修改值,而是在使用 enumerate() 时修改值

C:链表哈希表填充问题

python - Python GET 请求的 SSL 错误

python - 限制伪随机python列表中的重复次数

缺少 Python.h header