简体   繁体   English

如何遍历嵌套列表的一部分?

[英]How do I iterate over a slice of nested list?

I have this nested list: 我有这个嵌套列表:

nested = [[1, 1, 1], [2, 2, 2], [3, 3, 3]]

I wanted to subtract 1 from the first 2 elements of the inner list so I tried it with list comprehension: 我想从内部列表的前2个元素中减去1,所以我尝试了列表理解:

nested = [[x - 1 for x in stack[0:2]] for stack in nested]

It did give me back the first 2 elements subtracted by 1 for the inner lists but it removed the last element completely 它确实给了我返回内部列表的前2个元素减去1的信息,但它完全删除了最后一个元素

nested = [[0, 0], [1, 1], [2, 2]]

I thought that by slicing the list, it will not affect the other element. 我认为通过切片列表,不会影响其他元素。 However in this case it didn't work. 但是在这种情况下,它不起作用。 Can someone explain this to me? 谁可以给我解释一下这个?

To keep the 3rd element, include it in the list comprehension: 要保留第三个元素,请将其包括在列表理解中:

>>> [ [x - 1 for x in stack[0:2]] + stack[2:] for stack in nested ]
[[0, 0, 1], [1, 1, 2], [2, 2, 3]]

The above works for stack of any length. 以上适用于任何长度的stack

Or, if stack always has exactly three elements: 或者,如果堆栈始终完全具有三个元素:

>>> [[x-1, y-1, z] for x, y, z in nested]
[[0, 0, 1], [1, 1, 2], [2, 2, 3]]

Or, you can make the changes in place: 或者,您可以进行适当的更改:

>>> for stack in nested: stack[0]-=1; stack[1]-=1
... 
>>> nested
[[0, 0, 1], [1, 1, 2], [2, 2, 3]]

Another option is to use numpy which does this sort of slicing naturally 另一个选择是使用numpy ,它自然地进行这种切片

import numpy as np
nested = np.array([[1, 1, 1], [2, 2, 2], [3, 3, 3]])

nested[:,:2] -= 1

returns 退货

array([[0, 0, 1],
       [1, 1, 2],
       [2, 2, 3]])

Try it like this: 像这样尝试:

nested = [[x - 1  if i < 2 else x for i,x in enumerate(stack)] for stack in nested]

This will affect only first two elements keeping the rest as is. 这将只影响前两个元素,其余元素保持原样。

You can use enumerate : 您可以使用enumerate

nested = [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
new_nested = [[a-1 if i == 0 or i == 1 else a for i, a in enumerate(b)] for b in nested]

Output: 输出:

[[0, 0, 1], [1, 1, 2], [2, 2, 3]]

Edit: alternative, with map : 编辑:替代,与map

nested = [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
new_nested = [map(lambda x:x-1, i[:2])+[i[-1]] for i in nested]

Output: 输出:

[[0, 0, 1], [1, 1, 2], [2, 2, 3]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM