SimPy模块Store资源无法完全清空问题求助
问题根源
你的代码中,取货逻辑用了for item in store.items循环执行store.get(),但SimPy的Store.items是动态列表,每次store.get()会从列表头部移除元素。Python的for循环遍历列表时,迭代器基于初始列表的索引,当列表在遍历过程中被修改(元素被移除),会导致迭代错位——比如初始有11个元素,循环只能执行6次,最终剩下5个物品,这完全符合你提供的数据。
解决方案
不要直接遍历动态变化的store.items,而是先记录取货时刻的库存数量,再循环对应次数完成取货,确保取走该时间点的所有物品。
修改后的itemCollector函数如下:
def itemCollector(env, pickupTimes): while True: yield env.timeout(next(pickupTimes) - env.now) i = len(pickupData) pickupData.loc[i, 'timeBeforePickup'] = env.now pickupData.loc[i, 'itemsInStoreBefore'] = len(store.items) # 关键修改:先记录当前库存数量,再循环取货 current_stock = len(store.items) for _ in range(current_stock): yield store.get() pickupData.loc[i, 'timeAfterPickup'] = env.now pickupData.loc[i, 'itemsInStoreAfter'] = len(store.items)
扩展说明
如果你的需求是彻底清空Store,包括取货过程中新生产的物品(即使取货时间会被延长),可以改用while循环直到Store为空:
# 替代上面的for循环 while len(store.items) > 0: yield store.get()
这种方式会持续取货,直到Store中没有物品,但注意此时timeAfterPickup会晚于timeBeforePickup,因为取货过程中生产者可能继续生成新物品,需要等待这些物品被放入后再取走。
内容的提问来源于stack exchange,提问作者Yozef
相关产品推荐
相关产品推荐

