【发布时间】:2021-09-21 04:14:18
【问题描述】:
我正在重新访问如何在 Python 中编写以迭代数组列表,并且我正在尝试检查上一个和下一个值,并打印出列表中的当前值。例如,在我的列表中,我有 ["NotActive", "Active", "Depart", "Land", "Arrived"]
默认值为“NotActive”,我试图将 currentValue 设为“Depart”,我想检查下一个值为“Land”,前一个值为“Active”。但是,我一直将当前值设为“土地”
我创建了一个可以遍历列表的 for 循环。它会迭代,但不确定为什么如果一直迭代它就不会到达 Arrived。
知道发生了什么
status_array = request.data['status'] -> here is the list fields listed above
result = "NotActive" -> default value which now is the current value
try:
for name in status_array:
status = Flight.objects.get(name=name)
status_id = status.status_id
except Flight.DoesNotExist:
listed_result = {
"result": status_id
} -> here is the status_array for request.data['status'] the request going to be print out
print(listed_result) = ["Landed"]
【问题讨论】:
-
您可以使用enumerate 在循环中访问列表中的上一个和下一个值。
-
for previous, current, next in zip(data, data[1:], data[2:]): -
在代码中你应该使用
#insitead of->。或至少# ->将其作为评论。
标签: python django-rest-framework iterator