numpy 在Python中为列表元素指定阈值

k3bvogb1  于 2023-05-22  发布在  Python
关注(0)|答案(3)|浏览(135)

我打印一个列表CI基于某些操作如下所示。我尝试为子列表中的每个元素指定一个threshold值,如果该值小于此threshold,则它将选择此值。但我得到一个错误。我给出了预期的输出。

import numpy as np
km = [1, 2, 3, 4, 5]
CI=[]
threshold=0.005

for t in range(0, 2):
    CI_t = []
    for i in range(0, len(km)):
        CI1 = 0.001 * (1 - np.exp(-km[i] * t))
        CI_t=threshold if CI_t < threshold
        CI_t.append(CI1)
    CI.append(CI_t)
print("CI =",CI)

错误是

CI_t=threshold if CI_t < threshold[i]
                                         ^
SyntaxError: invalid syntax

预期输出为

CI = [[0.0, 0.0, 0.0, 0.0, 0.0], [0.005, 0.005, 0.005, 0.005, 0.005]]
koaltpgm

koaltpgm1#

使用min()函数,您可以将CI1与阈值进行比较,并选择它们之间较小的值。这确保如果CI1小于阈值,则将选择它;否则,将选择阈值。

for i in range(0, len(km)):
    CI1 = 0.001 * (1 - np.exp(-km[i] * t))
    CI1 = min(CI1, threshold)  # Apply the threshold condition here <<
    CI_t.append(CI1)
7gyucuyw

7gyucuyw2#

此代码将生成您指定的输出。每个t值都有一个子列表,但出于演示目的,我将代码改为一个循环。

import numpy as np

km = [1, 2, 3, 4, 5]
CI = []
threshold = 0.005

for t in range(0, 1):
    CI_t  = []
    for i in range(0, len(km)):
        CI1 = 0.001 * (1 - np.exp(-km[i] * t))
        if CI1 > threshold:
            CI.append(CI1)

        else:
            CI1 = 0.005
            CI_t.append(CI1),CI.append(0.0)
           
  
    CI = ([CI,CI_t])
print("CI =",CI)
tsm1rwdh

tsm1rwdh3#

下面是正确的代码:

import numpy as np

km = [1, 2, 3, 4, 5]
CI = []
threshold = 0.005

for t in range(0, 2):
    CI_t = []
    for i in range(0, len(km)):
        CI1 = 0.001 * (1 - np.exp(-km[i] * t))
        if CI1 < threshold:
            CI_t.append(CI1)
    CI.append(CI_t)
print("CI =", CI)

输出:

CI = [[0.0, 0.0, 0.0, 0.0, 0.0], [0.0006321205588285577, 0.0008646647167633873, 0.0009502129316321361, 0.0009816843611112657, 0.0009932620530009146]]

您可以根据自己的要求对这些值进行四舍五入。

相关问题