gpt4 book ai didi

python - 从 Python 2D 列表中删除列的最佳/快速方法

转载 作者:太空狗 更新时间:2023-10-30 01:44:08 24 4
gpt4 key购买 nike

我在 python 中有一个列表列表(所有列表都具有相同的大小),如下所示:

A = [[1,2,3,4],['a','b','c','d'] , [12,13,14,15]]

我想删除一些列(所有列表的第 i 个元素)。

没有 for 语句,有什么方法可以做到这一点吗?

最佳答案

如前所述,您不能在没有循环的情况下执行此操作。但是,这里使用内置函数是一种不显式使用任何循环的函数式方法:

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)

关于python - 从 Python 2D 列表中删除列的最佳/快速方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54503298/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com