2017-09-21 108 views
2

任何人可以試着幫我找回在Python數量和每個號碼數組: 我也做了下面的代碼,它的工作,但它顯示的是10爲兩個數字:如何使用python2.7從文本文件中讀取數據?

with open("test.dat") as infile: 
    for i, line in enumerate(infile): 
     if i == 0: 
      for x in range(0, len(line)): 
       if(line[x] == ' ' or line[x] == " "): 
        continue 

       else: 
        print(x, " " , line[x], ", ") 
        initial_state.append(line[x]) 

---結果:

(0, ' ', '1', ', ') 
    (2, ' ', '2', ', ') 
    (4, ' ', '3', ', ') 
    (6, ' ', '4', ', ') 
    (8, ' ', '5', ', ') 
    (10, ' ', '6', ', ') 
    (12, ' ', '7', ', ') 
    (14, ' ', '8', ', ') 
    (16, ' ', '9', ', ') 
    (18, ' ', '1', ', ') 
    (19, ' ', '0', ', ') 
    (21, ' ', '1', ', ') 
    (22, ' ', '1', ', ') 
    (24, ' ', '1', ', ') 
    (25, ' ', '2', ', ') 
    (27, ' ', '1', ', ') 
    (28, ' ', '3', ', ') 
    (30, ' ', '1', ', ') 
    (31, ' ', '4', ', ') 
    (33, ' ', '1', ', ') 
    (34, ' ', '5', ', ') 
    (36, ' ', '0', ', ') 
    (37, ' ', '\n', ', ') 

指數包含空格,請參閱數字IM線試圖如果你一定要添加到陣列

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 0 

回答

1

使用.split(),以通過循環分割各個領域,請看下面的代碼,它應該這樣做

with open("test.dat") as infile: 
     for i, line in enumerate(infile): 
      if i == 0: # if first line 
       field = [field.split(" ") for field in line.split(" ")] 

       for x in range(0, len(field)): 
        initial_state_arr.append(field[x]) 
+0

謝謝,這就是我要尋找 –

1

每個數字由單個空格分隔爲什麼不分割線並打印出每個元素的數組:

with open("test.dat") as infile: 
    content = infile.read().split() 
    for index, number in enumerate(content): 
     print ((index*2, number)) 

什麼是您的實際輸入和預期的結果?數字之間的文件是否有多個空格?

相關問題