替换Python中子列表内的数值

huangapple go评论60阅读模式
英文:

Replacing values within sublists in Python

问题

Here is the translated code segment:

我编写了一个循环如下所示但对于```sigma```的每个子列表元素我希望确保如果该值小于```threshold_sigma```,则应替换为```threshold_sigma```。我提供当前和期望的输出

```python
import numpy as np

km = [1, 2, 3, 4, 5]
CI = []
sigma0 = 0.021
R = 8.314
Temp = 295
K = 1.5e3
sigma = []
threshold_sigma = 0.005

for t in range(0, 3):
    CI_t = []
    sigma_t = []
    alpha_t = []
    Pr_cap_t = []
    for i in range(0, len(km)):
        CI1 = 0.001 * (1 - np.exp(-km[i] * t))
        CI_t.append(CI1)

        sigma1 = sigma0 - R * Temp * 0.001 * np.log(1 + K * 1.0 * CI_t[i])
        if sigma1 < threshold_sigma:
            sigma1 = threshold_sigma
        sigma_t.append(sigma1)

    CI.append(CI_t)
    sigma.append(sigma_t)
print("sigma =", sigma)

当前输出为

sigma = [[0.021, 0.021, 0.021, 0.021, 0.021], [-1.6146492190972785, -2.0186136083750714, -2.1519399869949933, -2.199220054620485, -2.2163866261027207], [-2.0186136083750714, -2.199220054620485, -2.222671745347101, -2.225828428605512, -2.2262553272687082]]

期望的输出是

sigma = [[0.021, 0.021, 0.021, 0.021, 0.021], [0.005, 0.005, 0.005, 0.005, 0.005], [0.005, 0.005, 0.005, 0.005, 0.005]]

<details>
<summary>英文:</summary>

I ma writing a loop as shown below but for every sublist element of ```sigma```, I want to ensure that if the value is less than ```threshold_sigma```, it should be replaced with ```threshold_sigma```. I present the current and expected output.

import numpy as np

km = [1, 2, 3, 4, 5]
CI = []
sigma0=0.021
R=8.314
Temp=295
K=1.5e3
sigma=[]
threshold_sigma=0.005

for t in range(0, 3):
CI_t = []
sigma_t=[]
alpha_t=[]
Pr_cap_t=[]
for i in range(0, len(km)):
CI1 = 0.001 * (1 - np.exp(-km[i] * t))
CI_t.append(CI1)

    sigma1=sigma0-R*Temp*0.001*np.log(1+K*1.0*CI_t[i])     
    sigma_t.append(sigma1)
    
CI.append(CI_t)
sigma.append(sigma_t)   

print("sigma =",sigma)


The current output is

sigma = [[0.021, 0.021, 0.021, 0.021, 0.021], [-1.6146492190972785, -2.0186136083750714, -2.1519399869949933, -2.199220054620485, -2.2163866261027207], [-2.0186136083750714, -2.199220054620485, -2.222671745347101, -2.225828428605512, -2.2262553272687082]]


The expected output is

sigma = [[0.021, 0.021, 0.021, 0.021, 0.021], [0.005, 0.005, 0.005, 0.005, 0.005], [0.005, 0.005, 0.005, 0.005, 0.005]]


</details>


# 答案1
**得分**: 0

将“sigma_t.append(sigma1)”替换为“sigma_t.append(max(sigma1,threshold_sigma))”在你的代码中。

<details>
<summary>英文:</summary>

You are almost there just replace `sigma_t.append(sigma1)` with `sigma_t.append(max(sigma1,threshold_sigma))` in your code

</details>



huangapple
  • 本文由 发表于 2023年5月21日 13:25:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/76298410.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定