简体   繁体   English

列表中最小的数字-Python

[英]Smallest Number in a List - Python

I am trying to write a function that takes a list input and returns the index of the smallest number in that list. 我正在尝试编写一个函数,该函数接受列表输入并返回该列表中最小数字的索引。 For example, 例如,

minPos( [5,4,3,2,1] ) → 4

When I run my function, I get a List Index error, can someone please help? 运行函数时,出现列表索引错误,有人可以帮忙吗? Thanks. 谢谢。 I cannot use the built in function min(). 我无法使用内置函数min()。

def MinPos(L):
     Subscript = 0
     Hydrogen = 1
     SmallestNumber = L[Subscript]

    while L[Subscript] < len(L):
          while  L[Subscript] < L[Subscript + Hydrogen]:
                Subscript += 1
                return SmallestNumber

          while L[Subscript] > L[Subscript + Hydrogen]:
                Subscript += 1

    return SmallestNumber


def main():
    print MinPos( [-5,-4] )

Maybe something like this: 也许是这样的:

>>> def min_pos(L):
...    min = None
...    for i,v in enumerate(L):
...        if min is None or min[1] > v:
...            min = (i,v)
...    return min[0] if min else None


>>> min_pos([1,3,4,5])
0

>>> min_pos([1,3,4,0,5])
3

Edit: Return None if empty list 编辑:如果为空列表,则返回None

Since you already know how to find the minimum value, you simply feed that value to the index() function to get the index of this value in the list. 由于您已经知道如何找到最小值,因此只需将其输入给index()函数即可获取该值在列表中的索引。 Ie, 也就是说,

>>> n = ([5,4,3,2,1])
>>> n.index(min(n))
4

This will return the index of the minimum value in the list. 这将返回列表中最小值的索引。 Note that if there are several minima it will return the first. 请注意,如果有多个最小值,它将返回第一个。

I would recommend use of for ... and enumarate() : 我建议使用for ...enumarate()

data = [6, 3, 2, 4, 2, 5]

try:
    index, minimum = 0, data[0]
    for i, value in enumerate(data):
        if value < minimum:
            index, minimum = i, value
except IndexError:
    index = None
print index
# Out[49]: 2

EDIT added guard against empty data 编辑添加了防止空data保护措施

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM