简体   繁体   English

Python 中多个 while 循环退出条件的模式

[英]Pattern for multiple while loop exit conditions in Python

I spent some time looking through similarly named questions on here, but none seem to address the question of what to do if you have multiple exit conditions, each with their own logical path after exit.我花了一些时间在这里查看类似命名的问题,但似乎没有一个问题可以解决如果您有多个退出条件该怎么办,每个退出条件都有自己的逻辑路径。 Here's what I mean.这就是我的意思。

I got started thinking about this while writing a function to add an element to a unique-element linked list:我在编写 function 以将元素添加到唯一元素链表时开始考虑这个问题:

class Node:
    def __init__(self, key, next=None, count=1):
        self.key = key       # Unique key corresponding to this node
        self.next = next     # Reference to next node in linked list
        self.count = count   # Occurrences of key above in data


node = get_prepopulated_list()

# Iterate over linked list until element is found or list is exhausted
while node.key != key and node.next is not None:
    node = node.next

# If found element, increment counter for that element
if node.key == key:
    node.count += 1

# Else, add new node to end
else:
    node.next = Node(key)

Notice how at least one of the two exit conditions is checked again after exit, leading to code duplication.请注意在退出后如何再次检查两个退出条件中的至少一个,从而导致代码重复。 Sure, we could flip which condition is being checked, but still there will remain code duplication.当然,我们可以翻转正在检查的条件,但仍然会有代码重复。

In this case, we could use something like this, which might be a bit cleaner:在这种情况下,我们可以使用这样的东西,它可能会更简洁一些:

node = get_prepopulated_list()

# Iterate over linked list until element is found or list is exhausted
while node.key != key and node.next is not None:
    try:
        node = node.next
    # Break out on 'None' condition
    except AttributeError:
        break

# Use implicit 'None' check from try-except to add new node to end on None
else:
    node.next = Node(key)
    return

# Otherwise, found element, so increment counter for that element
node.count += 1

But this isn't really any better, first because it adds a required escape during the else of the while-else , second because it adds some bloated error handling inside the loop, and finally because it breaks rule 2 of the Zen of Python: "Explicit is better than implicit".但这实际上并没有更好,首先因为它在elsewhile-else期间添加了必需的转义,其次因为它在循环内添加了一些臃肿的错误处理,最后因为它违反了 Python 的 Zen 规则 2: “显式胜于隐式”。 Beyond that, it's also not extensible to more than 2 exit conditions.除此之外,它也不能扩展到超过 2 个退出条件。

So I have two questions:所以我有两个问题:

  1. Is there a better way of handling such a case with 2 exit conditions and matching logical paths?有没有更好的方法来处理具有 2 个退出条件和匹配逻辑路径的这种情况?
  2. Is there a better way of handling the case with 3 or more exit conditions and matching logical paths?是否有更好的方法来处理具有 3 个或更多退出条件和匹配逻辑路径的情况?
while node.next is not None:
    if node.key != key: 
        node = node.next
    else:
        node.count += 1
        return

node.next = Node(key)

Note: will work only if get_prepopulated_list() is not None注意:仅当 get_prepopulated_list() 不是 None 时才有效

Minimal, Reproducible Example最小的、可重现的例子

class Node:
    def __init__(self,key):
        self.key = key
        self.next = None
        self.count = 1

class LinkedList:
    def  __init__(self):
        self.head = None

    def add(self,key):
        if self.head is None:
            self.head = Node(key)
        else:
            node = self.head
            while node.next is not None:
                if node.key != key: 
                    node = node.next
                else:
                    node.count += 1
                    return

            node.next = Node(key)

    def show(self):
        node = self.head
        while node is not None:
            print(node.key,'-->',node.count)
            node  = node.next
ll = LinkedList()

ll.add(5)
ll.add(6)
ll.add(2)
ll.add(5)
ll.add(7)
ll.show()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM