从列表列表中删除选定的元素列

时间:2016-08-29 11:01:09

标签: list

我有一个列表列表,其中每个列表都有3个元素。像这样:

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

如何删除特定列中的所有元素?例如,如果我输入“1”将删除第一列,如果我输入“2”,它将删除第二列,依此类推。

2 个答案:

答案 0 :(得分: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

希望有所帮助。

答案 1 :(得分: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