python - How to handle a KeyError when working with a list inside a list
问题描述
I have written two functions in Python that I intend to re-use multiple times. Together they will allow me to calculate the total travel distance of a vehicle in a warehouse collecting goods from defined locations in a single aisle.
One function get_orderpick
extracts two lists from input data in a dataFrame and returns them in a list, so the return clause looks like this: return [orderList, pickList]
.
When I run this function alone I appear to get a list with two lists stored inside it, no problem. BUT when I attempt to feed this through to my next function I get a KeyError.
So as I mentioned, the first function get_orderpick
appears to work just fine, here's the full code:
def get_orderpick(df):
# Produce a standard Python list of the picks
# DataFrame -> numpy.array -> list
pickList = df.sku.values.tolist()
orderList = df.order.values.tolist()
return [orderList, pickList]
Note - orderList
is the sequence of picks, I need to track when the vehicle must return to base and start over again on the next order. It contains only numbers; pickList
is the bay from which the pick must take place, this determines how far the vehicle must travel for each pick and contains a single capital letter in each entry.
Here is the distance calculation function:
def picking_distance(lists, layout):
orderList = lists[1] #<------------------ issue here
pickList = lists[2]
totalDistance = 0 # distance
currentPos = 0 # position
for i in range(len(pickList)):
if orderList[i] == 1 and currentPos != 0:
# new order, return to base
totalDistance += currentPos
currentPos = 0
i -= 1 # begin the pick from base again
else:
nextPos = layout[pickList[i]]
delta = abs(nextPos - currentPos)
totalDistance += delta
currentPos = nextPos
return totalDistance
I would expect the code to produce the total distance traveled. But I get a KeyError when I try to separate out the orderList
and pickList
from the lists
list. I am calling the functions together in the following way:
print(picking_distance(layout, get_orderpick(data)))
Thanks for your help!
P.S. I pass through a dictionary called layout
on the second function. This determines the distance between picking locations.
解决方案
所以......我犯了一个错误,在调用我自己的函数时改变了我的论点。
这意味着我正在传递一个字典,该函数需要一个列表列表。
切换参数已经解决了这个问题,而且效果很好。
print(picking_distance(get_orderpick(data), layout))
故事的道德启示
如果在您希望处理列表时遇到字典错误……您可能以错误的顺序传递参数。
谢谢你的时间!:D
推荐阅读
- kotlin - 本地期末班
throwable 的问题:类 在科特林 - java - 使用 Apache Avro 的 Avro 阵列
- node.js - 在 Jenkins 中获取 hudson.remoting.ChannelClosedException 错误
- python - 如何使用 FastAPI python 对用户进行身份验证
- automated-tests - 如何通过 Python 访问 Vector CANoe Simulation 中的 Interactive Generator 模块(IG)?
- jsfiddle - 通过 CDN 在 jsfiddle 中渲染 vue2leaflet 地图
- c# - C# 推断构造期间通过 Ref 参数分配的成员的可空性
- pandas - 无法从共享点导入数据框(错误)
- python-3.x - Jupyter notebook:内核突然重启
- php - 使用 WP_Query 显示 WooCommerce 自定义结帐字段