gpt4 book ai didi

python - while循环需要特定的命令才能工作?

转载 作者:行者123 更新时间:2023-12-03 16:11:10 25 4
gpt4 key购买 nike

当我使用以下代码时,我会得到正确的答案28。

#want to find sum of only the positive numbers in the list
#numbers = [1,3,9,10,-1,-2,-9,-5]
numbers = [4,6,2,7,9]
numbers.sort(reverse = True) # sets to greatest to smallest numbers
total = 0
_index = 0
#while numbers[_index] > 0 and _index < len(numbers):
while _index < len(numbers) and numbers[_index] > 0:
total += numbers[_index]
_index += 1
print(total)

当我尝试以下代码时,出现“IndexError:列表索引超出范围”,我只更改了while循环。为什么必须先出现一个条件,在运行此循环之前不检查每个条件?
#want to find sum of only the positive numbers in the list
#numbers = [1,3,9,10,-1,-2,-9,-5]
numbers = [4,6,2,7,9]
numbers.sort(reverse = True) # sets to greatest to smallest numbers
total = 0
_index = 0
while numbers[_index] > 0 and _index < len(numbers):
#while _index < len(numbers) and numbers[_index] > 0:
total += numbers[_index]
_index += 1
print(total)

最佳答案

您问题的答案称为短路评估。

如果复合条件AND语句的第一部分评估为False,那么在AND条件的情况下第二部分不评估。

如果条件是OR条件,则如果第一部分的计算结果为True,则检查条件的第二部分没有任何意义。

在您的情况下使用索引。如果长度已经超过数组的长度,并且首先检查情况就是如此-您将永远不会超出范围:

# here if the index is out of bounds we won't procede to access the elements
while _index < len(numbers) and numbers[_index] > 0:

如果您首先尝试访问数组中的元素,则可能会超出范围。

关于python - while循环需要特定的命令才能工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62338758/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com