[英]How to slice a nested list twice?
With a nested list like:使用嵌套列表,例如:
ex_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
I need to be able to slice this list for:我需要能够将此列表切片为:
[[1, 2], [4, 5]]
I've been trying:我一直在尝试:
list(ex_list[:2][:2])
but this isn't working.但这不起作用。 I'm obviously doing something very wrong but haven't been able to find a solution as using commas doesn't work either for some reason.我显然做错了一些事情,但由于某种原因使用逗号也不起作用,因此无法找到解决方案。
You need to slice the elements separately to the outer list;您需要将元素单独切片到外部列表; it's better to do the outer list first to avoid unnecessary inner slices.最好先做外部列表以避免不必要的内部切片。
[inner[:2] for inner in ex_list[:2]]
You should try using comprehension: Try:你应该尝试使用理解:尝试:
[i[:2] for i in ex_list[:2]]
Code:代码:
ex_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print([i[:2] for i in ex_list[:2]])
Output: Output:
[[1, 2], [4, 5]]
Is using numpy
an option?使用numpy
是一个选项吗?
import numpy as np
ex_list = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(ex_list[:2,:2].tolist()) # [[1, 2], [4, 5]]
The first :2
slice the outer list, the second slice each one of the inner lists.第一个:2
切片外部列表,第二个切片每个内部列表。
You can try map
你可以试试map
l = list(map(lambda lst: lst[:2], ex_list))
print(l)
[[1, 2], [4, 5], [7, 8]]
Or with itemgetter
或者使用itemgetter
from operator import itemgetter
l = list(map(itemgetter(slice(0,2)), ex_list))
print(l)
[[1, 2], [4, 5], [7, 8]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.