python - 如何在Python中管理列表

标签 python list

这是我的两个列表:

l1 = ['5', '10', '15', '20', '25', '30', '35', '40', '45']
l2 = ['0.011530', '0.039914', '0.085069', '0.145798', '0.213572', '0.287898', '0.355587', '0.413209', '0.472346']

感谢这两个列表,我想创建两个具有相同值但有一些更改的列表:

new_list1 = [5,10,10,15,15,20,20,25,25,30,30,35,35,40,40,45,45]
new_list2 = ['0.011530', '0.011530', '0.039914', '0.039914', '0.085069', '0.085069', '0.145798', '0.145798', '0.213572', '0.213572', '0.287898', '0.287898', '0.355587', '0.355587', '0.413209', '0.413209', '0.472346']

这两个新列表的目的是创建一个图表,而不是一条线,我将得到步骤。
[我不想要的]
1

[我想要什么]
2

作为初学者,我写道:

def test():
 
  new_list1.insert(0,l1[0])
  new_list2.insert(0,l2[0])

  new_list1.insert(1,l1[1])
  new_list2.insert(1,l2[0])

  new_list1.insert(2,l1[1])
  new_list2.insert(2,l2[1])

  new_list1.insert(3,l1[2])
  new_list2.insert(3,l2[1])

  new_list1.insert(4,l1[2])
  new_list2.insert(4,l2[2])
  
  new_list1.insert(5,l1[3])
  new_list2.insert(5,l2[2])

  new_list1.insert(6,l1[3])
  new_list2.insert(6,l2[3])

  new_list1.insert(7,l1[4])
  new_list2.insert(7,l2[3])
  
  new_list1.insert(8,l1[4])
  new_list2.insert(8,l2[4])

  new_list1.insert(9,l1[5])
  new_list2.insert(9,l2[4])

  new_list1.insert(10,l1[5])
  new_list2.insert(10,l2[5])
  
  new_list1.insert(11,l1[6])
  new_list2.insert(11,l2[5])

  new_list1.insert(12,l1[6])
  new_list2.insert(12,l2[6])

  new_list1.insert(13,l1[7])
  new_list2.insert(13,l2[6])
  
  new_list1.insert(14,l1[7])
  new_list2.insert(14,l2[7])

  new_list1.insert(15,l1[8])
  new_list2.insert(15,l2[7])

  new_list1.insert(16,l1[8])
  new_list2.insert(16,l2[8])

  print(new_list1)
  print(new_list2)

  x = np.array(new_list1) 
  y = np.array(new_list2)
  
  # plotting
  plt.title("Line graph") 
  plt.xlabel("X axis") 
  plt.ylabel("Y axis") 
  plt.plot(x, y, color ="green") 
  plt.show()

这很有趣,但我希望它更“漂亮”并且易于阅读,并带有一些“for”循环。 我怎样才能做到这一点?

最佳答案

您可以这样使用plt.step(x,t):

import matplotlib.pyplot as plt

l1 = ['5', '10', '15', '20', '25', '30', '35', '40', '45']
l2 = ['0.011530', '0.039914', '0.085069', '0.145798', '0.213572', '0.287898', '0.355587', '0.413209', '0.472346']

x = [int(v) for v in l1]
y = [float(k) for k in l2]

plt.step(x, y)

enter image description here

关于python - 如何在Python中管理列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66993764/

相关文章:

c# - 如何一次将预制件添加到列表中

python - 求和二维的最简单方法? (Python)

android - 无法在 Kivy 中为动画选择 id

python - 如何调整pygame中的图像大小以到达屏幕的顶部/底部?

python - 迭代多个列表并将其用作值增长字典

python - 在 python 中从解析的网页创建列表

Python素数计算器

python - 如何对同一列中的字段进行减法 - Python

python - Pandas 聚合数据,同时携带一列不变

python - 如何用python编写加密程序