【发布时间】:2021-08-28 09:14:58
【问题描述】:
我想为我的数组的值添加一个特定的数字,最大上限为 255,但仅限于数组中的数字与 0 不匹配的情况。
假设我要添加到数组中每个数字的值是 20,除非数字是 0
#The array to which I want to add a number based on value:
v=array([0,0,0,0,117,119,120,121,16,1,16,10,245,0,0,0,4,5])
value=20
lim = 255 - value
v[v > lim] = 255
v[v <= lim] += value
#Results in the following array
array([20,20,20,20,137,139,140,141,36,21,36,30,255,20,20,20,24,25])
这可行,但当数字为 0 时也会添加。但是,我想在其中添加一个语句,在所有情况下都添加 20,除非数组中的数字为 0!预期结果:
array([0,0,0,0,137,139,140,141,36,21,36,30,255,0,0,0,24,25])
无法找到好的解决方案或弄清楚如何解决。
【问题讨论】:
标签: python arrays list numpy list-comprehension