>>> lowest_path_cost = float('inf')
>>> # pretend that these were calculated using some worthwhile algorithm
>>> path_costs = [1, 100, 2000000000000, 50]
>>> for path in path_costs:
... if path < lowest_path_cost:
... lowest_path_cost = path
...
>>> lowest_path_cost
1
嗨,我在这里遇到了这个问题,想知道为什么if path < lowest_path_cost: lowest_path_cost = path
会在列表中生成最低值,因为它们都小于无穷大
为什么这有助于找到最低值?提前致谢。
正如@Selcuk 指出的那样(尽管我会稍微纠正一下),如果您想在一个循环中遍历所有项目,则可能需要有一个初始值。
你可以考虑这个问题;假设您有一个包含 1000 个数字的列表,即您无法一次查看所有数字。你如何用笔和纸找到最小的数字?其中一种方法是执行以下操作:
x0
)x1
,看看是否x1<x0
x0=x1
iex1
现在是新的最小数字在 python 中,这将是
#example 1)
numbers = [10,5,2,15,20....] #Long list
x0 = x[0] #first number
for x1 in numbers[1:]: #for all the remaining numbers [5,2,15,20...]
if x1 <x0: #check if the current number is less than the smallest number
x0 = x1 #if it is - update the smallest number to x1
但如果你不想使用列表中的第一个数字来初始化,你可以用你知道数量大于初始化任何数量的列表,它是inifinity
#example 2)
numbers = [10,5,2,15,20....] #Long list
x0 = float("int") # 'first' number
for x1 in numbers: #for all the remaining numbers- note we have removed the slicing [1:]
if x1 <x0: #check if the current number is less than the smallest number
x0 = x1 #if it is - update the smallest number to x1
然后你可能会问 - 为什么它必须是无穷大?让我们尝试举一个大数字的例子,比如 50.000。如果列表中的所有项目都大于 50.000,我们将得到列表中最小的项目是 50.000,这是错误的:
numbers = [100_000,200_000] #List with big numbers
x0 = 50_000 # Chose a too small number for initial-value
for x1 in numbers: #for all numbers
if x1 <x0: #None of the numbers in the list fulfill this check i.e x0 is never updated!
x0 = x1
print(x0)
#50_000
因此,唯一被视为所有列表的有效初始值的“数字”是
a) 列表中的第一个数字(示例 1)
b) 无穷大(例 2)
注意,例如2并没有当我们在列表中只有一个项目打破-如果我们在清单零个项目它打破。
但幸运的是,我们可以通过min(numbers)
@juanpa.arrivillaga 所说的那样调用来避免这一切
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句