Printing output in the form of multiple sublist within a list in Python

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

Printing output in the form of multiple sublist within a list in Python

问题

sigma_t=[]
alpha_t=[]
for t in range(0,2): 
    temp=[]
    for i in range(0,len(km)): 
        sigma1=sigma0-R*T*0.001*np.log(1+K*Cb*(1-np.exp(-km[i]*t)))
        if sigma1 < threshold_sigma:
            sigma1 = threshold_sigma
        temp.append(sigma1)
    sigma_t.append(temp)
英文:

I am appending all the values to list sigma_t using the loop below. However, I want the values to be within a sublist for each t. I present the current and expected output.

import numpy as np
sigma0=0.021
R=8.314
T=295
K=1.5e3
Cb=0.001
km=[1,2,3,4,5]
threshold_sigma=0.005

sigma_t=[]
alpha_t=[]
for t in range(0,2): 
    for i in range(0,len(km)): 
        sigma1=sigma0-R*T*0.001*np.log(1+K*Cb*(1-np.exp(-km[i]*t)))
        if sigma1 &lt; threshold_sigma:
            sigma1 = threshold_sigma
            
        sigma_t.append(sigma1)
    
        
print(sigma_t) 

The current output is

[0.021, 0.021, 0.021, 0.021, 0.021, 0.005, 0.005, 0.005, 0.005, 0.005]

The expected output is

[[0.021, 0.021, 0.021, 0.021, 0.021], [0.005, 0.005, 0.005, 0.005, 0.005]]

答案1

得分: 1

你在第二个循环中向sigma_t列表附加值,然后在代码末尾打印sigma_t。因此,你的所有值都存储在一个名为sigma_t的列表中。

为了使输出与期望的输出匹配,创建一个中间列表,在该列表中插入数据,并在执行第一个循环结束后,将该中间列表插入sigma_t并清空中间列表。

类似于这样:

for t in range(0, 2):
    temp_list = []
    for i in range(0, len(km)):
        sigma1 = sigma0 - R * T * 0.001 * np.log(1 + K * Cb * (1 - np.exp(-km[i] * t)))
        if sigma1 < threshold_sigma:
            sigma1 = threshold_sigma
        temp_list.append(sigma1)
    sigma_t.append(temp_list)

print(sigma_t)
英文:

You're appending values to sigma_t list inside your 2nd for loop, and then at the end of your code you're printing sigma_t. Hence you have all values sitting inside one list sigma_t.

For output to match the expected output, create an intermediate list, insert data in that list, and after you're done executing first for loop, insert that intermediate list in sigma_t and clear the intermediate list.

Something like this

for t in range(0,2):
    temp_list = []
    for i in range(0,len(km)): 
        sigma1=sigma0-R*T*0.001*np.log(1+K*Cb*(1-np.exp(-km[i]*t)))
        if sigma1 &lt; threshold_sigma:
            sigma1 = threshold_sigma
            
        temp_list.append(sigma1)
    sigma_t.append(temp_list)
    
        
print(sigma_t) 

huangapple
  • 本文由 发表于 2023年5月22日 18:33:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/76305287.html
匿名

发表评论

匿名网友

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

确定