在Python中切片列表列表 [英] slicing list of lists in Python
本文介绍了在Python中切片列表列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要在python中切片列表列表.
I need to slice a list of lists in 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.
我想要的是:[[1,2,3],[1,2,3],[1,2,3]]
推荐答案
使用numpy十分简单-您可以执行切片:
With numpy it is very simple - you could just perform the slice:
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]])
您当然可以将numpy.array
转换回list
:
In [4]: A[:,:3].tolist()
Out[4]: [[1, 2, 3], [1, 2, 3], [1, 2, 3]]
这篇关于在Python中切片列表列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文