如前所述,没有循环就无法做到这一点。但是,这里使用内置函数是一种不显式使用任何循环的函数式方法:
In [24]: from operator import itemgetter
In [25]: def remove_col(arr, ith):
...: itg = itemgetter(*filter((ith).__ne__, range(len(arr[0]))))
...: return list(map(list, map(itg, arr)))
...:
演示:
In [26]: remove_col(A, 1)
Out[26]: [[1, 3, 4], ['a', 'c', 'd'], [12, 14, 15]]
In [27]: remove_col(A, 3)
Out[27]: [[1, 2, 3], ['a', 'b', 'c'], [12, 13, 14]]
请注意,如果您只返回map(itg, arr),而不是list(map(list, map(itg, arr))),它将给您预期的结果,但作为迭代器的迭代器而不是列表的列表。在这种情况下,就内存和运行时间而言,这将是一种更优化的方法。
另外,使用循环是我这样做的方式:
In [31]: def remove_col(arr, ith):
...: return [[j for i,j in enumerate(sub) if i != ith] for sub in arr]
令人惊讶的是(如果您相信 C 的强大功能,则不会 :))函数式方法对于大型数组来说甚至更快。
In [41]: arr = A * 10000
In [42]: %timeit remove_col_functional(arr, 2)
8.42 ms ± 37.9 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
In [43]: %timeit remove_col_list_com(arr, 2)
23.7 ms ± 165 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
# And if in functional approach you just return map(itg, arr)
In [47]: %timeit remove_col_functional_iterator(arr, 2)
1.48 µs ± 4.71 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)