Skip to main content
 首页 » 编程设计

python之在python列表中找到最小值

2025年05月04日12lidabo

我想在列表中找到最小值。我知道我可以使用 min(),但我正在学习 Python 并想自己实现它来练习:

x=[2,3,5,9,1,0,2,3] 
z=len(x)-1 
i=0 
for i in range(z): 
    if x[i]<x[i+1]: 
        y=x[i] 
    else: 
        y=x[i+1] 
print(y) 

虽然这没有找到最小值。我如何更改它以找到列表 x 中的最小值?

请您参考如下方法:

尝试停止使用整数索引列表。遍历列表要容易得多。

x = [2,3,5,9,1,0,2,3] 
 
def my_min(sequence): 
    """return the minimum element of sequence""" 
    low = sequence[0] # need to start with some value 
    for i in sequence: 
        if i < low: 
            low = i 
    return low 
 
print my_min(x)