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

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

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

问题

  1. sigma_t=[]
  2. alpha_t=[]
  3. for t in range(0,2):
  4. temp=[]
  5. for i in range(0,len(km)):
  6. sigma1=sigma0-R*T*0.001*np.log(1+K*Cb*(1-np.exp(-km[i]*t)))
  7. if sigma1 < threshold_sigma:
  8. sigma1 = threshold_sigma
  9. temp.append(sigma1)
  10. 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.

  1. import numpy as np
  2. sigma0=0.021
  3. R=8.314
  4. T=295
  5. K=1.5e3
  6. Cb=0.001
  7. km=[1,2,3,4,5]
  8. threshold_sigma=0.005
  9. sigma_t=[]
  10. alpha_t=[]
  11. for t in range(0,2):
  12. for i in range(0,len(km)):
  13. sigma1=sigma0-R*T*0.001*np.log(1+K*Cb*(1-np.exp(-km[i]*t)))
  14. if sigma1 &lt; threshold_sigma:
  15. sigma1 = threshold_sigma
  16. sigma_t.append(sigma1)
  17. print(sigma_t)

The current output is

  1. [0.021, 0.021, 0.021, 0.021, 0.021, 0.005, 0.005, 0.005, 0.005, 0.005]

The expected output is

  1. [[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并清空中间列表。

类似于这样:

  1. for t in range(0, 2):
  2. temp_list = []
  3. for i in range(0, len(km)):
  4. sigma1 = sigma0 - R * T * 0.001 * np.log(1 + K * Cb * (1 - np.exp(-km[i] * t)))
  5. if sigma1 < threshold_sigma:
  6. sigma1 = threshold_sigma
  7. temp_list.append(sigma1)
  8. sigma_t.append(temp_list)
  9. 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

  1. for t in range(0,2):
  2. temp_list = []
  3. for i in range(0,len(km)):
  4. sigma1=sigma0-R*T*0.001*np.log(1+K*Cb*(1-np.exp(-km[i]*t)))
  5. if sigma1 &lt; threshold_sigma:
  6. sigma1 = threshold_sigma
  7. temp_list.append(sigma1)
  8. sigma_t.append(temp_list)
  9. 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:

确定