简体   繁体   English

在 python 中索引多维数组

[英]indexing multidimensional array in python

I have an array like below and I want to keep only the 3rd element for each row.我有一个如下所示的数组,我只想保留每行的第三个元素。

Input输入

array(['a', 'b', 'c'], ['a1', 'b1', 'c1'],........['an', 'bn', 'cn'])

Expected output预期 output

array('c', 'c1', ...... 'cn')

I tried it using a for loop but it is taking too long.我尝试使用 for 循环,但耗时太长。 Is there a faster way to do this?有没有更快的方法来做到这一点? Can someone please help?有人可以帮忙吗?

Assuming that you mean a list when you mention an array .假设您在提到array时指的是list

This would be the code:这将是代码:

>>> my_list = [['a', 'b', 'c'], ['a1', 'b1', 'c1'], ['an', 'bn', 'cn']]
>>> [x[2] for x in my_list]
['c', 'c1', 'cn']
>>> 

The code编码

[x[2] for x in my_list]

pointed out by Gab is correct, however if you are making use of an numpy array, this will be probably more efficent: Gab 指出是正确的,但是如果您使用的是 numpy 阵列,这可能会更有效:

x[:,2]

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

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