Richard Rublev
Richard Rublev

Reputation: 8172

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?

Upvotes: 0

Views: 63

Answers (1)

Kirill Bulygin
Kirill Bulygin

Reputation: 3826

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()

Upvotes: 4

Related Questions