微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在检查数组中的上一个和下一个值时仅检索当前元素python

如何解决如何在检查数组中的上一个和下一个值时仅检索当前元素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"]

解决方法

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

,

如果您只想检查上一个和下一个,您可以为前一个设置临时变量。

#Set the previous/next to empty
prev = ''
next = ''
for i in range(len(status_array)):
    #Check if we are at the end
    if status_array[i] == 'Arrived':
        #Get the previous information
        status_prev = Flight.objects.get(name=prev)
        prev_status_id = status_prev.status_id
        #Get the current information
        status = Flight.objects.get(name=status_array[i])
        status_id = status.status_id
    #Check to see if we are at the start
    if prev == '':
        next = status_array[i+1]
        status_next = Flight.objects.get(name=next)
        next_status_id = status_next.status_id
        #Set the current to be the previous
        prev = status_array[i]
        #Get the current status info
        status = Flight.objects.get(name=status_array[i])
        status_id = status.status_id

    #Else we have a previous
    else:
        #Get the previous information
        status_prev = Flight.objects.get(name=prev)
        prev_status_id = status_prev.status_id
        #Get the current information
        status = Flight.objects.get(name=status_array[i])
        status_id = status.status_id
        #Make sure we have not 'Arrived'
        if status_array[i] != 'Arrived':
            next = status_array[i+1]
            status_next = Flight.objects.get(name=next)
            next_status_id = status_next.status_id
        #Update the previous
        prev = status_array[i]

我希望这指向正确的方向,但如前所述,使用双向链表进行尝试会更容易。干杯!

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。