如何定义next_objects方法,获取集合中对象的邻近元素quantity数组?
实现
next_objects方法的解决方案 需求明确
需要定义方法next_objects(object, object_index, objects),核心逻辑如下:
- 以当前元素在集合中的索引
object_index为起点,向后取最多object.neighbours个元素 - 收集这些元素的
quantity属性,组成数组返回 - 若后续元素不足指定数量,取到集合末尾为止;若
object.neighbours为0,直接返回空数组
示例匹配验证
结合给出的示例数据:
- id为340的元素(集合索引为2),
neighbours=6,后续6个元素的quantity依次为13、19、18、37、88、42,返回数组[13,19,18,37,88,42] - id为343的元素(集合索引为5),
neighbours=2,后续2个元素的quantity为37、88,返回数组[37,88] - id为344的元素(集合索引为6),
neighbours=0,返回空数组[]
代码实现(以Python为例)
首先模拟示例中的对象结构:
class Item: def __init__(self, id, quantity, neighbours): self.id = id self.quantity = quantity self.neighbours = neighbours # 构建示例集合 objects = [ Item(338, 60, 3), Item(339, 40, 2), Item(340, 29, 6), Item(341, 13, 1), Item(342, 19, 4), Item(343, 18, 2), Item(344, 37, 0), Item(345, 88, 1), Item(346, 42, 0), ]
实现next_objects方法:
def next_objects(obj, obj_index, objects): # 计算起始索引:当前索引的下一位 start_idx = obj_index + 1 # 计算结束索引:起始索引 + 要取的元素数量,自动不超过集合长度 end_idx = start_idx + obj.neighbours # 切片获取目标元素,提取quantity属性组成数组 return [item.quantity for item in objects[start_idx:end_idx]]
测试验证
# 测试id340的场景 item_340 = objects[2] print(next_objects(item_340, 2, objects)) # 输出: [13, 19, 18, 37, 88, 42] # 测试id343的场景 item_343 = objects[5] print(next_objects(item_343, 5, objects)) # 输出: [37, 88] # 测试id344的场景 item_344 = objects[6] print(next_objects(item_344, 6, objects)) # 输出: []
关键逻辑说明
- 利用列表切片
objects[start_idx:end_idx]自动处理边界问题:如果end_idx超出集合长度,切片会自动取到最后一个元素;如果start_idx已经等于或超过集合长度,切片返回空列表 - 列表推导式直接提取目标属性,代码简洁高效
内容的提问来源于stack exchange,提问作者Jerome
相关产品推荐
相关产品推荐

