Python - 列表中的列表中删除列


在列表中的列表中,每个子列表中位于相同索引下的元素表示类似列的结构。在本文中,我们将了解如何从列表中的列表中删除一列。这意味着我们必须从每个子列表的相同索引位置删除元素。

使用 pop

我们使用 pop 方法,该方法会移除指定位置的元素。设计了一个 for 循环,以遍历指定索引处的元素并使用 pop 将其移除。

示例

 实时演示

# List of lists
listA = [[3, 9, 5, 1],
[4, 6, 1, 2],
[1, 6, 12, 18]]

# printing original list
print("Given list \n",listA)

# Apply pop
[i.pop(2) for i in listA]

# Result
print("List after deleting the column :\n ",listA)

输出

运行上述代码,我们得到以下结果 -

Given list
[[3, 9, 5, 1], [4, 6, 1, 2], [1, 6, 12, 18]]
List after deleting the column :
[[3, 9, 1], [4, 6, 2], [1, 6, 18]]

使用 del

此方法中我们使用 del 函数,该函数与上述方法类似。我们提及要删除列的索引。

示例

 实时演示

# List of lists
listA = [[3, 9, 5, 1],
[4, 6, 1, 2],
[1, 6, 12, 18]]

# printing original list
print("Given list \n",listA)

# Apply del
for i in listA:
del i[2]

# Result
print("List after deleting the column :\n ",listA)

输出

运行上述代码,我们得到以下结果 -

Given list
[[3, 9, 5, 1], [4, 6, 1, 2], [1, 6, 12, 18]]
List after deleting the column :
[[3, 9, 1], [4, 6, 2], [1, 6, 18]]

更新于: 2020-07-10

986 次浏览

开启你的职业生涯

完成认证课程

开始
广告
© . All rights reserved.