2013-10-05 68 views
0

我有一個文件,我已經讀入列表中存儲xyz座標以在pygame中繪製線條。從python pygame的列表中刪除字符

此文件的格式如下:

-2000 -2000 -2000 # THE FRAME, origin point, 1 
-2000 379 -2000 # 2 
2000 379 -2000 # 3 
2000 -2000 -2000 # 4 
-2000 -2000 -2000 # 1 
j 
2000 379 -1190 # 7 
2000 -2000 -1190 # 8 
-2000 -2000 -1190 # 5 

我只需要存儲到一個列表一切我不需要數字和第j(跳躍)。我會如何編碼這個?

我曾嘗試以下,但不能得到它的工作:

with open('C:\\Python33\\PIXB.DAT', 'r') as file: 
    for line in file: 
     line = line.split('#') 

我運行的代碼,並去除了從我的名單整個第一行:

-2000 -2000 -2000 # THE FRAME, origin point, 1 

然後將剩下我值仍然有#(後跟一個數字旁邊

我渴望以下的輸出:

[' -2000 -2000 -2000\n', ' -2000 379 -2000\n', ' 2000 379 -2000\n', ' 2000 -2000 -2000\n', ' -2000 -2000 -2000', 'J\n', ' 2000 -2000 -1190\n', '  2000 -2000 -1190\n',] 

我要像一個輸出(上面),所以我可以把它變成一組與J有序對變成一個跳躍有點像(下圖):

[-2000, -2000, -2000],[-2000, 379, -2000],[2000, 379, -2000],[2000, -2000, -2000],[-2000, -2000, -2000],[JUMP],etc... 
+0

使用'str.split()' – aIKid

+0

你試過[_anything_](http://mattgemmell.com/2008/12/08/what-have-you-tried/)嗎? – martineau

+0

我試過.split(),但它刪除了我的第一行值[-2000 -2000 -2000#FRAME,原點,1]並將所有其他#留在原地 – user2840327

回答

0

如果你只是想前三從線(比j線除外)號,這裏是你可以做什麼:

results = [] 
with open('C:\\Python33\\PIXB.DAT', 'r') as file: 
    for line in file: 
     values = line.split() # splits on any whitespace 
     if len(values) > 1 # not the j line 
      results.extend(values[:3]) # add three values to the results list 
     else: 
      results.append(values[0]) # add the "j" to the list 

對於示例數據,這將給results等於:

['-2000','-2000','-2000','-2000','379','-2000','2000','379','-2000','2000',' -2000','-2000','-2000','-2000','j','2000','379','-1190','2000','-2000', 「-1190」,「-2000」,「-2000」,「-1190」]

如果你希望把每行三個數值爲整數,而不是把它們當做字符串,你可以改變extend撥打以上爲:

results.extend(int(x) for x in values[:3]) 

如果你想每行三個數保持在一起,而不是在結果列表平整出來,改變extendappend(如果將值轉換爲int s,則將tuple(...)[...]放在發生器表達式的周圍)。