我有一個從 CSV 文件中讀取的四元組列表,其元素的形式為 t =(id, e1, e2, label)。該列表應包含每個 t 元組:(someID, e2,e1, 3-label)。如果沒有,我需要添加到列表中。我編寫了以下代碼并將我的列表縮小到只有 50 個元組。import nltkimport csv#file stringfs = "mydataset.csv"with open(fs) as infile: rows = list(csv.reader(infile))[950:1000] size = len(rows) print("initial size =", size) newSize = size firstId = int(rows[1][0]) lastId = int(rows[size-1][0]) for i in range(size): if i % 500 == 0: rint("program progression = ", i*100/size, '%', sep ='') tempRow = rows[i] if tempRow[-1] == '1' or tempRow[-1] == '2': for j in range(i+1, size): # print("j = ", j) if tempRow[1] == rows[j][2] and tempRow[2] == rows[j][1]: if int(tempRow[3]) == 3-int(rows[j][3]): break else: print("error in row: ", i) else: if j == size -1: lastId +=1 print(tempRow[-1]) rows += rows +[[ str(lastId), tempRow[2], tempRow[1], str(3-int(tempRow[3])) ]] newSize +=1 print("newSize", newSize) print("END")當我運行它時,它會耗盡我的內(nèi)存。它使用超過8GB的內(nèi)存?請問這是怎么回事?我的 CSC 文件只有 7200 行 4 列。我真的不知道我還能做什么。
2 回答

萬千封印
TA貢獻1891條經(jīng)驗 獲得超3個贊
不知道,但這條線看起來很可疑:
rows += rows +[[ str(lastId), tempRow[2], tempRow[1], str(3-int(tempRow[3])) ]]
我無法猜測您在這里嘗試做什么,但是這條線不太可能實現(xiàn)您的意圖。這使每次執(zhí)行的長度增加了一倍rows多,并且您的代碼中似乎沒有任何內(nèi)容可以減少rows.
使理解要點變得非常簡單:
>>> rows = [1]
>>> for i in range(20):
... rows += rows
... print(i, len(rows))
顯示:
0 2
1 4
2 8
3 16
4 32
5 64
6 128
7 256
8 512
9 1024
10 2048
11 4096
12 8192
13 16384
14 32768
15 65536
16 131072
17 262144
18 524288
19 1048576

皈依舞
TA貢獻1851條經(jīng)驗 獲得超3個贊
非常感謝!你說對了。我不得不做刪除+!
rows = rows +[[ str(lastId), tempRow[2], tempRow[1], str(3-int(tempRow[3])) ]]
添加回答
舉報
0/150
提交
取消