test_list = [[4, 5, 6, 8],
[2, 7, 10, 9],
[12, 16, 18, 20]]
如果我想从列表中删除第 2 列,即 [5,7,16],我知道我可以使用:
[j.pop(1) for j in test_list]
但是,如果我想同时移动2列,即[5,7,16]和[8,9,20],我该如何更改代码,所以结果是:
The modified mesh after column deletion : [[4, 6], [2, 10], [12, 18]]
答案 0 :(得分:1)
这是另一种方式:
columns_to_remove = (1,3)
new_object = [[x for i,x in enumerate(l) if i not in columns_to_remove] for l in test_list]
请注意,这会在不修改原始 test_list
的情况下创建一个新对象。
答案 1 :(得分:0)
test_list = [[4, 5, 6, 8], [2, 7, 10, 9],[12, 16, 18, 20]]
removeIndex = [1,3] # The indices you want to remove
for l in test_list:
for i,v in enumerate(removeIndex):
l.pop(v-i)
print(test_list)
答案 2 :(得分:0)
您可以尝试使用所需索引进行列表理解 注意:我没有改变原始列表,它正在创建全新的列表
test_list = [[4, 5, 6, 8],
[2, 7, 10, 9],
[12, 16, 18, 20]]
[[i[0], i[2]] for i in test_list]
[[4, 6], [2, 10], [12, 18]]
答案 3 :(得分:0)
您可以使用 numpy 轻松完成:
import numpy as np
test_list = [[4, 5, 6, 8],
[2, 7, 10, 9],
[12, 16, 18, 20]]
a = np.array(test_list)
a = np.delete(a, [1,3], axis=1)
print(a)
#output:
[[ 4 6]
[ 2 10]
[12 18]]
答案 4 :(得分:0)
您可以使用 numpy 数组删除多列。请查看 numpy.delete() 以获取文档。
import numpy as np
test_list = [[4, 5, 6, 8],
[2, 7, 10, 9],
[12, 16, 18, 20]]
a = np.array(test_list)
a = np.delete(a, [1, 3], axis=1)
print (a)
输出将是:
[[ 4 6]
[ 2 10]
[12 18]]
如果要删除一列或一组列,也可以将 numpy.delete 与 slice() 结合使用。
如果你想删除第二和第三列,你可以给:
np.delete(a, slice(1, 3), axis=1)
array([[ 4, 8],
[ 2, 9],
[12, 20]])
如果要删除第 2 列和第 4 列,可以使用 slice(start, stop, skip) 选项如下:
np.delete(a, slice(1, None,2), 1)
输出将是:
array([[ 4, 6],
[ 2, 10],
[12, 18]])
如果您希望将 numpy 数组作为列表的常规列表存储回来,您可以随时执行 a.tolist()