python - 替换列表中的所有负值

标签 python python-3.x

我试图在 codewars 上解决这个问题,但我完全被难住了:

y = [-1, -1, 2, 8, -1, 4]
z = [1,3,5]
#to create [1,3,2,8,5,4]

我该怎么做?

我尝试过:

for e in range(len(y)):
    try:
        if y[e] < 0:
            y[e] = z[e]
    except:
        pass

但这只有在底片对应于 z 中的内容时才有效。

最佳答案

如果您确定负数的数量始终等于 z,您可以将 z 转换为可迭代对象并使用列表理解来创建新列表:

In [9]: z = iter(z)

In [10]: [next(z) if i < 0 else i for i in y]
Out[10]: [1, 3, 2, 8, 5, 4]

请注意,如果 z 的长度小于负数的数量,则会引发 StopIteration 错误。

关于python - 替换列表中的所有负值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39441323/

相关文章:

python - 如何访问列表字典中的每个元素?

python - (Python3) flask 管理员: It is possible to full utilise the table to view data

Python:根据条件对字典中的值求和

python - 更好地说明闭包?

python - 创建以键作为变量名的 Python 字典的简写

python - 通过 Elixir 使用多个数据库

python - openCV 3中contourArea的兼容性问题

python - 使用 BOTO-Python 列出表的 Amazon DynamoDB 中的所有主索引和辅助索引

Python 类中的数组构造

python - 使用 Pandas 或其他方式将元组列表转换为相关矩阵