2016-08-29 39 views
1

我有一個列表,其中每個列表中有3個元素。類似這樣的:從列表中刪除選定的列元素

[[928.7, 554.29999958311, 0], 
[928.7, 558.15990063549, 0], 
[914.1, 558.15990063549, 0], 
[914.1, 554.29999958311, 0]] 

如何從特定列中刪除所有元素?例如,如果我輸入將刪除第一列的「1」,如果我輸入「2」,它將刪除第二列,依此類推。

回答

1

我假設你的問題關於pyhton ...

我會嘗試像以下(使用numpy的):

import numpy as np 

    initial_list = [[928.7, 554.29999958311, 0], 
        [928.7, 558.15990063549, 0], 
        [914.1, 558.15990063549, 0], 
        [914.1, 554.29999958311, 0]] 

    # transform the list in a numpy array 
    a = np.array(initial_list) 

    # remove the column you want and put the output in a new variable 
    a1 = np.delete(a, 0, 1) # this would the remove the first column(0) 
          #+the second "1" in the arguments tells to 
          #+numpy to delete the column instead of the 
          #+ row. 

    # convert back to a plain list 
    final_list = a1.tolist() 

如果你想留在普通的Python,我建議像:

initial_list = [[928.7, 554.29999958311, 0], 
        [928.7, 558.15990063549, 0], 
        [914.1, 558.15990063549, 0], 
        [914.1, 554.29999958311, 0]] 

    for row in initial_list: 
     del row[0] # This would delete the first column from your matrix 


    final_list = initial_list 

請注意後一種方法會「覆蓋」原始列表,並且您將丟失所有已刪除的數據。考慮如果你需要,創建一個initial_list的副本:

initial_list_bck[:] = initial_list[:] 
    # or 
    initial_list_bck = initial_list.copy() 
    # The following would create only a pointer to the first list 
    initial_list_bck = initial_list 

希望對你有所幫助。

0

遍歷列表的列表。白色迭代,刪除第n項。

a = [[928.7, 554.29999958311, 0], 
[928.7, 558.15990063549, 0], 
[914.1, 558.15990063549, 0], 
[914.1, 554.29999958311, 0]] 

column_number = 1 

for i in range(0, len(a)): 
    a[i].remove(a[i][column_number]) 

print a 
+0

這個答案肯定值得一點解釋! –

+0

幹得好!希望最好的OP喜歡它;) –