Richard Rublev Richard Rublev - 2 days ago 4
Python Question

How to extract list elements outside the loop?

My code

import matplotlib.pyplot as plt

with open('spec.out') as infile:
for line in infile:
nums = [float(i) for i in line.split()]
a1=nums[1]
a2=nums[2]

plt.plot(a2,a1,'r--')
plt.xlabel('frequency')
plt.ylabel('MTM Spectrum value')
plt.show()


The problem is that a1 and a2 are not visible for plotting.How to solve this?

Answer

Try this:

import matplotlib.pyplot as plt

a1 = []
a2 = []
with open('spec.out') as infile:
    for line in infile:
        nums = [float(i) for i in line.split()]
        a1.append(nums[1])
        a2.append(nums[2])

plt.plot(a2,a1,'r--')
plt.xlabel('frequency')
plt.ylabel('MTM Spectrum value')
plt.show()
Comments