首页 > 解决方案 > 如何在检查数组中的上一个和下一个值时仅检索当前元素(python)

问题描述

我正在重新访问如何在 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"]

标签: pythondjango-rest-frameworkiterator

解决方案


我想也许你可以考虑实现一个 Python DoubleLinkedList 类,这样你的数据就可以进入这个数据结构。

双链表包含几个节点,每个节点都有一个前一个节点和一个下一个节点。在一个节点中,我们可以存储数据。而且,在(公共)属性的帮助下,我们实际上可以从前一个节点或下一个节点检索数据,给定一个当前节点来引用。我的参考在这里


推荐阅读