2016-03-02 50 views
0

這裏是我到目前爲止已經試過如何在Python中以列表或數組的形式讀取負數?

with open('xy.txt') as f: 
    next(f, None) 
    alist = [line.rstrip()[1:19] for line in f] 
    print alist[0] 

with open('xy1.txt') as f: 
    next(f, None) 
    alist1 = [line.rstrip()[1:19] for line in f] 
    print alist1[0] 

with open('yx.txt') as f: 
    next(f, None) 
    alist = [line.rstrip()[1:19] for line in f] 
    print alist[0] 

with open('yx1.txt') as f: 
    next(f, None) 
    alist1 = [line.rstrip()[1:19] for line in f] 
    print alist1[0] 

當我運行代碼

5.509014339324e+03 
4.927809838950e+03 
6.440208621086e+03 
1.912637550671e+03 

但yx.txt有負數

>ZYXR //74 
-6.440208621086e+03 -4.758666382870e+03 -3.995858566350e+03 -4.934315690511e+03 -5.049765912718e+03 

如何解決這個問題?

回答

1

從0開始。Python序列是0索引的。通過使用[1:19],您可能會切斷第一個字符,即-

+1

是的,就是這樣,現在好的工作! –

1

我認爲你的問題可以通過使用函數split()來解決。這將以「單詞」分隔您的行,因此您應該正確讀取任何格式。

結果代碼將是:

with open('xy.txt') as f: 
    next(f, None) 
    alist = [line.split[0] for line in f] 
    print alist[0] 

with open('xy1.txt') as f: 
    next(f, None) 
    alist1 = [line.split[0] for line in f] 
    print alist1[0] 

with open('yx.txt') as f: 
    next(f, None) 
    alist = [line.split[0] for line in f] 
    print alist[0] 

with open('yx1.txt') as f: 
    next(f, None) 
    alist1 = [line.split[0] for line in f] 
    print alist1[0] 
相關問題