Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/332.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
了解Python的迭代特性”;在;for循环和if语句中的运算符_Python - Fatal编程技术网

了解Python的迭代特性”;在;for循环和if语句中的运算符

了解Python的迭代特性”;在;for循环和if语句中的运算符,python,Python,以下代码返回列表中第一个偶数值之前存在的列表“A”中值的总和 例如: 如果列表A=[1,3,5,4],结果将返回1+3+5=9 如果列表A=[1,2,5,4],结果将返回1 def for_version(L): found_even = False total = 0 for num in L: if num % 2 != 0 and not found_even: total = total + num els

以下代码返回列表中第一个偶数值之前存在的列表“A”中值的总和

例如:

如果列表A=[1,3,5,4],结果将返回1+3+5=9

如果列表A=[1,2,5,4],结果将返回1

def for_version(L):
    found_even = False
    total = 0

    for num in L:
        if num % 2 != 0 and not found_even:
            total = total + num
        else:
            found_even = True

    return total

A = [1,3,5,9]

for_version(A)
我不明白,在第一次迭代之后,我们如何不丢失列表中的第一个整数。换句话说,下面是我想象的代码是如何工作的

从列表“A”中的第一个值开始,并准备一次一个地遍历所有值:

for num in L:
检查if语句的第一次迭代:

if num % 2 != 0 and not found_even:
else:
     found_even = True
虽然列表中的第一个数字是奇数,但由于
found\u偶数
设置为
False
最初,代码应移到
else
语句:

if num % 2 != 0 and not found_even:
else:
     found_even = True
我猜想if语句现在已经在列表的第一个值上完成了,所发生的只是found_偶bool被更改为True

我以为代码会继续下去;然后在列表中的下一个值上测试if语句。然而,这似乎是不正确的。如果我的想法是正确的,在上面的例子中,这意味着在完成求和时将忽略列表“1”中的第一个值,我们将得到3+5=8而不是1+3+5=9

很明显,我不明白这个问题的基本原理

for num in L:
线路工程。。。实际上,它好像没有移动到列表中的下一个整数,并在列表中的第一个整数上重新运行代码。有人能解释一下这是为什么吗

虽然列表中的第一个数字是奇数,但由于
found\u偶数
被设置为
False
最初,代码应该移动到
else
语句[。]

你的逻辑就错了
notfalse
为true,因此
if
语句测试为true,而
else
套件不执行

您可以自己进行测试:

>>> num = 1  # odd
>>> found_even = False
>>> num % 2
1
>>> num % 2 != 0
True
>>> not found_even
True
>>> num % 2 != 0 and not found_even
True
代码本身过于复杂;早点回来。不需要迭代或使用标志<代码>返回结束函数和迭代:

def for_version(L):
    total = 0    
    for num in L:
        if num % 2 == 0:
            return total
        total += num
或者,使用
break
停止循环,然后返回

Python标准库在
itertools
库中有一个有用的工具,称为;它将为您提供iterable的所有元素,直到给定的测试失败。然后它将停止迭代:

from itertools import takewhile

sum(takewhile(lambda x: x % 2, A))

我删除了
!=0
在那里测试<代码>%2只会导致
0
1
0
在布尔测试中被视为假值。我还使用了将
经过的所有数字相加。

如果找到或没有第一个偶数,无需跟踪,只要在找到时中断并保留for循环即可:

for num in L:
    if num % 2 != 0:
        total = total + num
    else:
        break

精彩的解释!正如我所料,我是编程新手,对于if语句如何操作,这是一个非常基本的困惑。我错误地认为if语句测试了find_偶数变量的当前状态,并且仅当该状态与之前设置的状态匹配时才继续。实际上,if语句只是检查表达式当前的计算结果是否为“True”。如果有,它会开火,如果没有,它会移动到else。。。真的帮我解决了这个问题再次谢谢!也不知道为什么这个问题被否决了。。。尽我所能做到清晰和中肯;(