英文:
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 < 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 < threshold_sigma:
sigma1 = threshold_sigma
temp_list.append(sigma1)
sigma_t.append(temp_list)
print(sigma_t)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论