【问题标题】:How to end a While-Loop when value is met inside a Nested List in Python?在 Python 的嵌套列表中遇到值时如何结束 While 循环?
【发布时间】:2020-10-10 18:22:36
【问题描述】:

我有一个嵌套列表,当通过 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

【问题讨论】:

    标签: python-3.x list while-loop nested-loops


    【解决方案1】:

    你可以这样做:-

    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
    

    【讨论】:

    • 这很好用!但是,我想进一步了解,我可以看到变量“完成”是一个布尔值,我想知道它是如何有效的,而我的却不是,当它看起来很简单时?​​span>
    • 因为在您的代码中,程序位于“for 循环”内,而您的“while 条件”位于该“for 循环”之外。但在我的代码中,我在“for 循环”中设置了 break 语句
    • 我明白了。我有点明白了。感谢您清除它!
    【解决方案2】:

    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 循环将始终完全执行,并且 point 的值将始终是最后一组的最后一个值在列表中(在本例中为 '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 循环是不必要的。

    【讨论】:

    • 谢谢!现在它更清楚了,你的解释真的很棒。我不知道我可以在 For-Loop 中使用 Else 条件。
    • 很高兴它对您有所帮助。在 Python 中,您可以 :) 您可以在此处阅读更多相关信息:docs.python.org/3/tutorial/controlflow.html,第 4.4 节。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-08
    • 2015-06-30
    • 1970-01-01
    • 1970-01-01
    • 2013-05-21
    • 2020-10-09
    • 2016-06-14
    相关资源
    最近更新 更多