Python-使用测试列出理解以避免被零除 [英] Python - List comphrehension with test to avoid division by zero
本文介绍了Python-使用测试列出理解以避免被零除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
a
和b
是一维numpy数组(或python列表):
a
and b
are 1 dimensional numpy arrays (or python lists):
我正在这样做:
>>> c = [x/y for x,y in zip(a,b)]
b
有时其中有一个零-因此会出现被零除的错误.
Occasionally b
has a zero in it - so a division by zero error occurs.
如何有条件地检查b
中的0值并将c
的相应元素设置为0?
How can I conditionally check for a 0 value in b
and set the corresponding element of c
to 0?
推荐答案
You can use if-else
condition inside list comprehension:
>>> c = [x/y if y else 0 for x,y in zip(a,b)]
这篇关于Python-使用测试列出理解以避免被零除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文