我有以下共20行數據如果循環替換值
1 2 5 4 1
2 2 2 3 3
3 3 4 1 2
4 3 5 1 2
5 4 3 8 4
....
我希望能夠存儲每個列,並且要替換特定如果環條件一些值,並寫入行號,某些列中出現了多少個替換值。我寫了這樣的代碼
n_lines = 20
A = [None] * n_lines
B = [None] * n_lines
C = [None] * n_lines
D = [None] * n_lines
E = [None] * n_lines
with open ('output.txt', 'w') as outfile:
for i in range(n_lines): ### Read everything to data_lines
data_lines[i] = file.readline()
for j in range(n_lines): ### Read and store column by column
data = data_lines[j].split()
A[j] = int(data[0])
B[j] = int(data[1])
C[j] = int(data[2])
D[j] = int(data[3])
E[j] = int(data[4])
for k in range(n_lines): ### Analyze table
if B[k] == 2: ### Check if 2nd column's value is 2
c1 = C[k] ### If it is, read 3rd column and 4th column, store them as c1 and d1.
d1 = D[k]
if ((B[c1] == 4) and (B[d1] == 4)): ### Check if 2nd column's c1-th and d1-th values are 4
B[k] = 9 ### If those conditions are met, replace B[k] value from 2 to 9
elif ((D[c1] + E[d1] >= 10)):
B[k] = 10 #### If this condition is met, replace B[k] value from 2 to 10
num_9 = [B[k]].count(9) ### Count the occurrence number of replaced value 9
num_10 = [B[k]].count(10) ### Count the occurrence number of replaced value 10
out = '%5d'%k + '%5d'%num_9 + '%5d'%num_10 ### Print out
outfile.write(out)
outfile.write('\n')
outfile.close()
但我面對
if ((B[c1] == 4) and (B[d1] == 4)):
IndexError: list index out of range
我不明白爲什麼「超出範圍」錯誤發生。 'elif((D [c1] + E [d1]> = 10)):'line也發生了同樣的錯誤。所有列(A〜E)大小合適。我的方式if-loop表達式是錯誤的?或者我的替換方式是錯誤的? (我在同一格式的其它數據是在15000線100數據blcoks,所以希望使用用於環路用於索引保持。)
謝謝
你有數字矩陣,可以考慮在數據結構存儲他們像列表中,列表或'numpy.ndarray'。 – 2014-10-10 02:28:03
@BrianCain謝謝,但我沒有索引和訪問列表和數組形式列表中的每個元素(如http://stackoverflow.com/questions/26208434/multidimension-array-indexing-and-column-accessing),所以我決定使用這種形式。至少我對這裏的索引,訪問和分割/讀取命令感到更加舒適。 – exsonic01 2014-10-10 02:31:17