返回数组中项目两侧的元素

问题描述 投票:0回答:2

概述

编程难题因此与社区综合了这个解决方案。我已确保写得清楚,但仍需要进一步澄清

问题描述

给定一个数组 a

a = np.asarray([14, 12, 13, 14, 13, 10, 14, 6])

从数组中随机选择一个项目,ri

ri = 14

随机项ri有多个具有相同值的项,它们的索引在列表中ri_indexes

ri_indexes = [0, 3, 6]

任务:
对于 ri_indexes 上的每个项目,从其左侧或右侧返回 2 个元素。如果 ri_indexes 上的项目有索引 < 2, that means we may not get up to 2 elements from its left. Thus, it must return empty. Else return a list of the item and 2 elements from both of its sides.

例如,如果

ri_indexes[1] == 3

然后

a[3] == 14

a[3]左侧有 2 项;

12, 13
a[3]

右侧有 2 项; 13, 10

预期回报输出

[12,13, 14, 13,10]

喜欢与社区分享

python numpy indexing numpy-ndarray
2个回答
1
投票
a

函数,该函数接受数组 a、随机项

ri
和索引列表
ri_indexes
。然后,迭代 ri_indexes 中的每个索引,并对于每个索引,提取其左侧和右侧的两个元素(如果可用)。 这是一个实现此目的的 Python 函数:
def extract_neighbors(a, ri, ri_indexes):
    result = []
    for index in ri_indexes:
        if index < 2:
            # If index < 2, cannot get 2 elements from left
            neighbors_left = []
        else:
            neighbors_left = a[index - 2:index]

        if index + 2 >= len(a):
            # If index + 2 >= len(a), cannot get 2 elements from right
            neighbors_right = []
        else:
            neighbors_right = a[index + 1:index + 3]

        result.extend(neighbors_left + [ri] + neighbors_right)

    return result

# Example usage:
import numpy as np

a = np.asarray([14, 12, 13, 14, 13, 10, 14, 6])
ri_indexes = [0, 3, 6]
ri = a[ri_indexes[1]]

output = extract_neighbors(a, ri, ri_indexes)
print(output)  # Output: [12, 13, 14, 13, 10]



0
投票

import numpy as np def get_elements(a, ri_index): if ri_index < 2 or ri_index > len(a) - 3: return [] else: return a[ri_index - 2 : ri_index + 3] a = np.asarray([14, 12, 13, 14, 13, 10, 14, 6]) ri_indexes = [0, 3, 6] for ri_index in ri_indexes: print(get_elements(a, ri_index))

输出是:

[] [12 13 14 13 10] []

可能可以写成一句台词,但我认为这显示了思考过程。如果不完全是您需要的,请告诉我,以便我进行调整。

© www.soinside.com 2019 - 2024. All rights reserved.