简体   繁体   中英

how to returns the index of the smallest element in the list in python

In my code, returns the position of the smallest element in the list by use index() function, when I run the code, it run nothing. Please help me to figure out problem. Here is what I coded:

def get_index_of_smallest(numbers):
    smallest_index = []
    for element in range (len(numbers)):
        element = numbers.index(min(numbers))
        smallest_index = element + 1
    return smallest_index

def test_get_index_of_smallest():
    list1 = [23, 3, 6, 5, 12, 9, 7, 4]
    print(get_index_of_smallest(list1))

Many thanks.

You can use min(list) and builtin function of list ( list.index() )

list1 = [23, 3, 6, 5, 12, 9, 7, 4]
min_num = min(list1)
index = list1.index(min_num)

One way, it's possible using min , emumerate and lambda

myList = [23, 3, 6, 5, 12, 9, 7, 4]
min(enumerate(myList), key=lambda x:x[1])[0]
#1

Your code looks good, but you forgot to call the function. Add test_get_index_of_smallest() , and it will work!

Input:

def get_index_of_smallest(numbers):
    smallest_index = []
    for element in range (len(numbers)):
        element = numbers.index(min(numbers))
        smallest_index = element + 1
    return smallest_index

def test_get_index_of_smallest():
    list1 = [23, 3, 6, 5, 12, 9, 7, 4]
    print(get_index_of_smallest(list1))

test_get_index_of_smallest()

Output:

2

Edit: You can further cut down your code. Here is a code that does the same thing:

Input:

def get_index_of_smallest(numbers):
    return numbers.index(min(numbers))+1

print(get_index_of_smallest([23, 3, 6, 5, 12, 9, 7, 4]))

Output:

2

We can use list comprehension and enumerate here

min_idx = [idx for idx, item in enumerate(list1) if item == min(list1)]
 [1]

Here is a expanded version of what is going on here

for idx, item in enumerate(list1):
    if item == min(list1):
        min_idx = idx

When we enumerate in it iterates for the index and item so what we can do is check each item v min(list1) if we get a match we can set our min_idx variable to the corresponding index of that item , cheers !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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