簡體   English   中英

將具有多列的文件寫入數組

[英]Write files with multiple columns to array

我有幾個帶有x和y值的文件,我想同時將它們繪制到一張圖中。 為此,我想做一個循環,在該循環中,程序將寫入x數據和y數據,以便最終得到如下所示的數組:

results=[[x1],[y1],[x2],[y2],....]

之后,我想將所有數據繪制在一張圖中,但使用不同的顏色。 這是自動的。

編輯:我的代碼看起來像這樣:

#Program to show FFT intensitys of interfering waves with phase difference
path='pah_to_files'
files=['0pi.txt','0.25pi.txt','0.5pi.txt','0.75pi.txt','1pi.txt']

#read data
for i in range (len(files)):
    data=np.loadtxt(path+'/'+files[i], usecols=(0,1))
    position=data[:,0] #first column is position
    intensity=data[:,1] #second column is intensity

我知道此循環讀取文件,但始終會覆蓋以前的位置和強度數據。

更好的方法是使用zip ,如下所示:

x_values = [1,2,3,4,5]
y_values = ['a','b','c','d']
pairs_of_values = zip(x_values, y_values)

現在pairs_of_values[0]將是一個元組 (1,'a')

以下幾行可用於以您說的結果應具有的方式填充結果列表:

results = [];
for x in range(10):
    y = x*x
    results.append([x])
    results.append([y])

print results

抱歉,我使用Python已有4天了,我認為我必須更加小心列表和數組。...以下代碼解決了我在讀取文件時遇到的問題。

#Program to show FFT intensitys of interfering waves with phase difference
path='pah_to_files'
files=['0pi.txt','0.25pi.txt','0.5pi.txt','0.75pi.txt','1pi.txt']

results=[]

#read data
for i in range (len(files)): #all files which are tortured the folloing way
data=np.loadtxt(path+'/'+files[i], usecols=(0,1))

results.append(data[:,0]) #x-position
results.append(data[:,1]) #intensity

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM