我有一段代码可在Python 2.7中工作,但不能在Python3.7中工作。在这里,我试图按lambda函数的值进行排序。
def get_nearest_available_slot(self):
"""Method to find nearest availability slot in parking
"""
available_slots = filter(lambda x: x.availability, self.slots.values())
if not available_slots:
return None
return sorted(available_slots, key=lambda x: x.slotNum)[0]
我得到的错误是:
File "/home/xyz/Desktop/parking-lot/parking-lot-1.4.2/parking_lot/bin/source/parking.py", line 45, in get_nearest_available_slot
return sorted(available_slots, key=lambda x: x.slotNum)[0]
IndexError: list index out of range
我在这里做错了什么?
答案很简单:这是因为filter
工作原理。
在Python 2,filter
是急切地评估,这意味着一旦你怎么称呼它,它返回list
:
filter(lambda x: x % 2 == 0, [1, 2, 3])
输出:
[2]
相反,在Python 3中,它filter
是惰性的;它产生一个您可以迭代一次的对象,或一个迭代器:
<filter at 0x110848f98>
在Python 2中,if not available_slots
如果结果filter
为空,则该行停止执行,因为空list
值为False
。
但是,在Python 3中,filter
返回一个迭代器,该True
迭代器的总值为,因为在不尝试获取下一个元素的情况下您无法确定迭代器是否已耗尽,并且迭代器没有长度。请参阅此以获取更多信息。
因此,存在将空迭代器传递给并sorted
产生另一个empty的情况list
。您不能在0
空位置访问元素list
,因此会得到一个IndexError
。
为了解决这个问题,我建议严格评估条件。您可以执行以下操作,将其替换sorted
为min
,因为我们只需要一个值:
def get_nearest_available_slot(self):
"""Method to find nearest availability slot in parking
"""
available_slots = [slot for slot in self.slots.values() if slot.availability]
if available_slots:
return min(available_slots, key=lambda x: x.slotNum)
else:
return None
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句