如何在数组中保留特定元素索引

时间:2016-09-28 10:58:52

标签: python arrays list indexing

假设我有两个数组:

a = [1, 4, 9, 16, 25, 36, 49, 64, 81]
b = [2,5,7]

我希望将元素索引保存在b中列出的元素中,以便a:的第2,第5和第7个索引:

a_new = [4, 25, 49]

然后我将根据a_new /执行分析绘制b。

对于我的应用程序,a是一系列模拟数据,b是我想从这些数据中采样的时间序列。

由于

2 个答案:

答案 0 :(得分:2)

首先请记住,数组的第一个元素(或者在本例中是一个列表)是数字0而不是数字1:

a = [1, 4, 9, 16, 25, 36, 49, 64, 81]
a[0] = 1   # How to adress the first element
a[1] = 4   # How to adress the second element
a[2] = 9   # ...

所以你想要的元素(如数组b中所指定的)是:

a[1] = 4    # a[1] is the same as a[2 - 1] (note that b[0] = 2)
a[4] = 25   # a[4] is the same as a[5 - 1] (note that b[1] = 5)
a[6] = 49   # a[6] is the same as a[7 - 1] (note that b[2] = 7)

所以你也可以这样访问元素:

a[ b[0] - 1 ] = 4    # Same as a[1] which is the second element
a[ b[1] - 1 ] = 25   # Same as a[4] which is the fifth element
a[ b[2] - 1 ] = 49   # Same as a[6] which is the seventh element

这可以包含在for循环中:

a_new = []    # Start with an empty list
for index in b:   # index in b are all elements in b, thus: b[0] = 2, b[1] = 5 and b[2] = 7
    a_new.append(a[ index - 1])

此循环将元素a[2 - 1](4),a[5 - 1](25)和a[7 - 1](49)放入列表a_new

但是有一种更短的方式来编写该循环:

a_new = [ a[ index - 1] for index in b ]

基本上,您说a_new = [ ... ],因此a_new是一个列表,内部的...将指定列表将填充的内容。在这种情况下,它将是for循环产生的元素,请注意a[ index - 1] for index in b与第一个示例中的for循环相同,以紧凑的方式编写。

如果列表索引超出范围错误怎么办?
您的列表a包含9个元素,因此第一个元素是a[0],最后一个元素是a[8]。如果您尝试访问列表中的任何其他元素,例如a[12],则会出现“列表索引超出范围”错误。
这意味着:列表b应该只包含1到9之间的数字(列表的长度,您可以通过这种方式找到len[a] = 9)。

我建议,您将列表b更改为b = [1, 4, 6],因为数组的第五个元素实际上是a[4]而不是a[5]
代码会更容易一些:

a_new = [ a[index] for index in b ]

如果你不想发生错误,那么b中的值应该在0到8之间(len(a) - 1),因为a[0]是第一个而a[8]是最后一个元素,只有它之间的元素存在!

答案 1 :(得分:1)

您可能遇到两个可能的问题,这两个问题在评论中都有所提及。从我看到的情况来看,您在阅读时遇到问题,或者b中的索引无效。

对于前者,你可能真的想要

a = [1, 4, 9, 16, 25, 36, 49, 64, 81]
b = [2,5,7]

生产:

a_new = [9, 36, 64]

因为你总是从零开始计算:

[1, 4, 9, 16, 25, 36, 49, 64, 81]
 0  1  2  3   4   5   6   7   8

因此,导致XY problem,您尝试以错误的方式解决问题 。因此,我们浪费时间来尝试修复一个不起作用的问题,因为它实际上是其他东西。

但是,对于后者,您的b列表中可能存在异常。根据需要索引列表(在注释中给出)的方法是使用list comprehension

a_new = [a[i-1] for i in b]

这是做什么的:

a_new = []
for i in b:
    a_new.append(a[i-1])

因此,当i大于或等于len(a)时,它会评估为无效索引:

>>> a = [1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> len(a)
9
>>> a[9]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range
相关问题