如何在 Python 的嵌套列表中遇到值时结束 While 循环?

How to end a While-Loop when value is met inside a Nested List in Python?

我有一个嵌套列表,当通过 For 循环搜索嵌套循环内的值时,我试图结束 while 循环。我的问题是它一直在循环。

listA = [
['a','b'], # 0, -5
['b','c'], # 1, -4
['c','d'], # 2, -3
['a','d'], # 3, -2
['b','e'], # 4, -1
]

endpoint = 'c'
point = ''
while point is not endpoint:
    for sets in listA:
        for point in sets:
            print(point)

我希望输出是这样的:

a
b
b
c

你可以这样做:-

listA = [
['a','b'], # 0, -5
['b','c'], # 1, -4
['c','d'], # 2, -3
['a','d'], # 3, -2
['b','e'], # 4, -1
]

endpoint = 'c'
done = False
for sets in listA:
    if done:
        break
    for point in sets:
        print(point)
        if point == endpoint:
            done=True
            break

Yash 的回答就可以了。

另一种方法是定义一个函数并在点等于端点时返回。

listA = [
['a','b'], # 0, -5
['b','c'], # 1, -4
['c','d'], # 2, -3
['a','d'], # 3, -2
['b','e'], # 4, -1
]

endpoint = 'c'

def foo(items, endpoint):
    for sets in items:
        for point in sets:
            print(point)
            if point == endpoint:
                return

foo(listA, endpoint)

但是要回答你的问题为什么它不起作用,这是因为第二个 for 循环将始终完全执行并且点的值将 always列表中最后一组的最后一个值(在本例中为 'e')。所以这就是 while 循环将永远 运行 的原因,因为它将始终检查 'e' 是否不是 'c' 评估为真。

如果您想保留旧的解决方案,可以这样做:

listA = [
['a','b'], # 0, -5
['b','c'], # 1, -4
['c','d'], # 2, -3
['a','d'], # 3, -2
['b','e'], # 4, -1
]

endpoint = 'c'
point = ''
while point != endpoint:
    for sets in listA:
        for point in sets:
            print(point)
            if endpoint == point:
                break
        else: 
            continue
        break

point 等于 endpoint 时,它基本上是从嵌套的 for 循环中制动。

如您所见,您检查了点和端点是否相同两次(在 if endpoint == point 和 while 循环中),因此 while 循环是不必要的。