在 Python 中切片列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36436425/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
slicing list of lists in Python
提问by HuckleberryFinn
I need to slice a list of lists in python.
我需要在 python 中切片列表列表。
A = [[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5]]
idx = slice(0,4)
B = A[:][idx]
The code above isn't giving me the right output.
上面的代码没有给我正确的输出。
What I want is : [[1,2,3],[1,2,3],[1,2,3]]
我想要的是: [[1,2,3],[1,2,3],[1,2,3]]
回答by awesoon
With numpy it is very simple - you could just perform the slice:
使用 numpy 非常简单 - 你可以只执行切片:
In [1]: import numpy as np
In [2]: A = np.array([[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5]])
In [3]: A[:,:3]
Out[3]:
array([[1, 2, 3],
[1, 2, 3],
[1, 2, 3]])
You could, of course, transform numpy.array
back to the list
:
当然,您可以转换numpy.array
回list
:
In [4]: A[:,:3].tolist()
Out[4]: [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
回答by timgeb
Very rarely using slice objects is easier to read than employing a list comprehension, and this is not one of those cases.
很少使用切片对象比使用列表理解更容易阅读,这不是这些情况之一。
>>> A = [[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5]]
>>> [sublist[:3] for sublist in A]
[[1, 2, 3], [1, 2, 3], [1, 2, 3]]
This is very clear. For every sublist in A
, give me the list of the first four elements.
这是非常清楚的。对于 中的每个子列表A
,给我前四个元素的列表。
回答by Sid
you can use a list comprehension such as: [x[0:i] for x in A]
where i
is 1,2,3 etc based on how many elements you need.
您可以使用列表推导式,例如:根据您需要多少元素[x[0:i] for x in A]
,where i
is 1,2,3 等。
回答by Rahul Kumar
A = [[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5]]
print [a[:3] for a in A]
Using list comprehension
使用列表理解
回答by Technical jangra
I am new in programming and Python is my First Language. it's only 4 to 5 days only to start learning. I just learned about List and slicing and looking for some example I found your problem and try to solve it Kindly appreciate if my code is correct. Here is my codeA = [[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5]] print(A[0][0:3],A[1][0:3],A[1][0:3])
我是编程新手,Python 是我的第一语言。只需 4 到 5 天即可开始学习。我刚刚了解了 List 和切片,并在寻找一些示例,我发现了您的问题并尝试解决它 如果我的代码正确,请表示感谢。 这是我的代码A = [[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5]] print(A[0][ 0:3],A[1][0:3],A[1][0:3])
回答by Haifeng Zhang
Either:
任何一个:
>>> [a[slice(0,3)] for a in A]
[[1, 2, 3], [1, 2, 3], [1, 2, 3]]
Or:
或者:
>>> [list(filter(lambda x: x<=3, a)) for a in A]
[[1, 2, 3], [1, 2, 3], [1, 2, 3]]