2016-12-01 33 views
2

我的代碼如何提取循環外的列表元素?

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

的問題是,A1和A2是不可見的plotting.How來解決這個問題?

+1

之前'with'外初始化它們爲'None'即? –

+0

嘗試使用聲明之前聲明a1,a2。 –

回答

4

試試這個:

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