这是我的两个列表:
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']
这两个新列表的目的是创建一个图表,而不是一条线,我将得到步骤。
[我不想要的]
[我想要什么]
作为初学者,我写道:
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)
关于python - 如何在Python中管理列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66993764/