这是我在这里的第一个问题。问题很简单——
# this removes the top list from the list of lists
triangle = [
[3, 0, 0],
[2, 0, 0],
[1, 0, 0]]
del triangle[0]
我想有一个类似的简单方法来删除“列”。我当然可以使用 for 循环来做到这一点,但是是否有等同于
del triangle[0]
谢谢
请您参考如下方法:
如果您想在就地执行此操作而不复制整个列表,则类似
all(map(lambda x: x.pop(which_column), triangle))
编辑。是的,如果列中有 0,它将不起作用,只需使用任何其他累加器函数
sum(map(lambda x: x.pop(which_column), triangle))
对于 python 2,不需要 map 不是迭代器累加器:
map(lambda x: x.pop(1), triangle)
作为副作用,这将返回您可以使用的已删除列
deleted_column = list(map(lambda x: x.pop(which_column), triangle))
(不需要 python 2 list() 包装器)
更短的形式是
sum(i.pop(which_column) for i in triangle)
或
deleted_column = [i.pop(which_column) for i in triangle]
虽然我不确定它是否符合“没有 for 循环”的条件
附言在官方 Python 文档中,他们使用 0-lenqth deque 来使用迭代器,如下所示:
collections.deque(map(lambda x: x.pop(which_column), triangle), maxlen=0)
我不知道它是否比sum()更好,但它可以用于非数字数据
