从数组中的项目两侧返回元素[关闭]

问题描述 投票: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 indexing
2个回答
-1
投票

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] []

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


-1
投票

这可能就是您正在寻找的:

import random # numpy is irrelevant for the task at hand so let's just use lists def function(_list, _indices): result = [] for i in _indices: if i + 3 <= len(_list) and i - 2 >= 0: result.append(_list[i-2:i+3]) return result the_list = [14, 12, 13, 14, 13, 10, 14, 6] ri = random.choice(the_list) ri_indexes = [i for i, v in enumerate(the_list) if v == ri] print(ri, function(the_list, ri_indexes))

对于输入列表中的各种值,您将得到以下输出:

6 [] 10 [[14, 13, 10, 14, 6]] 12 [] 13 [[14, 12, 13, 14, 13], [13, 14, 13, 10, 14]] 14 [[12, 13, 14, 13, 10]]

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