- Pythonic way to find maximum value and its index in a list?
- 11 Answers 11
- Поиск максимального значения в списке на Python
- Список в Python
- №1 Нахождение максимального значения с помощью функции max()
- 5 Ways to Find the list max index in Python
- 1. Finding max index using for loop
- 2. Using built in methods – max() and index()
- 3. Using enumerate() function to find Python list max index
- 4. Finding max index for multiple occurrences of elements
- 5. Maximum index from a numpy array
- Python: как найти индекс максимального значения в списке
- Пример 1: поиск индекса максимального значения в списке
- Пример 2: поиск индекса максимального значения в списке со связями
Pythonic way to find maximum value and its index in a list?
If I want the maximum value in a list, I can just write max(List) , but what if I also need the index of the maximum value? I can write something like this:
maximum=0 for i,value in enumerate(List): if value>maximum: maximum=value index=i
@mwc: It will iterate the list once to determine the maximum value, then iterate it a second time to find the index of that value.
11 Answers 11
I think the accepted answer is great, but why don’t you do it explicitly? I feel more people would understand your code, and that is in agreement with PEP 8:
max_value = max(my_list) max_index = my_list.index(max_value)
This method is also about three times faster than the accepted answer:
import random from datetime import datetime import operator def explicit(l): max_val = max(l) max_idx = l.index(max_val) return max_idx, max_val def implicit(l): max_idx, max_val = max(enumerate(l), key=operator.itemgetter(1)) return max_idx, max_val if __name__ == "__main__": from timeit import Timer t = Timer("explicit(l)", "from __main__ import explicit, implicit; " "import random; import operator;" "l = [random.random() for _ in xrange(100)]") print "Explicit: %.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000) t = Timer("implicit(l)", "from __main__ import explicit, implicit; " "import random; import operator;" "l = [random.random() for _ in xrange(100)]") print "Implicit: %.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000)
Results as they run in my computer:
Explicit: 8.07 usec/pass Implicit: 22.86 usec/pass
Explicit: 6.80 usec/pass Implicit: 19.01 usec/pass
Didn’t expect it to be faster. It is faster even when I replace l with «l = [random.random() for _ in xrange(10000000)]+[2]», which guarantees that last element is the largest.
@Sunny88: For a simple list of numbers, the simple approach is faster. If you are after performance in this case, I’d suggest to use numpy.argmax() , which is another 30 times faster on my machine. If the list contains more complicated objects than mere numbers, the approach in my answer can become faster. Wnother advantage of that approach is that it can be used for arbitrary iterators, not only for lists.
@Sven-Marnach Would numpy be faster, if I had to convert my list to a numpy array first? Would it be faster for the simple example [0,1,0]?
@Sven-Marnach I just checked. numpy.argmax is by far the slowest method, and it gives the wrong answer, if the array contains strings instead of floats or integers.
There are many options, for example:
import operator index, value = max(enumerate(my_list), key=operator.itemgetter(1))
@Sunny88: The key function is only used to decide which element is maximal. The elements are not changed.
@lifebalance Using itemgetter() is faster, and avoiding an import isn’t a goal worth pursuing. Avoiding external dependencies can be worthwhile in some cases, but an import from the standard library is a non-issue.
This answer is 33 times faster than @Escualo assuming that the list is very large, and assuming that it’s already an np.array(). I had to turn down the number of test runs because the test is looking at 10000000 elements not just 100.
import random from datetime import datetime import operator import numpy as np def explicit(l): max_val = max(l) max_idx = l.index(max_val) return max_idx, max_val def implicit(l): max_idx, max_val = max(enumerate(l), key=operator.itemgetter(1)) return max_idx, max_val def npmax(l): max_idx = np.argmax(l) max_val = l[max_idx] return (max_idx, max_val) if __name__ == "__main__": from timeit import Timer t = Timer("npmax(l)", "from __main__ import explicit, implicit, npmax; " "import random; import operator; import numpy as np;" "l = np.array([random.random() for _ in xrange(10000000)])") print "Npmax: %.2f msec/pass" % (1000 * t.timeit(number=10)/10 ) t = Timer("explicit(l)", "from __main__ import explicit, implicit; " "import random; import operator;" "l = [random.random() for _ in xrange(10000000)]") print "Explicit: %.2f msec/pass" % (1000 * t.timeit(number=10)/10 ) t = Timer("implicit(l)", "from __main__ import explicit, implicit; " "import random; import operator;" "l = [random.random() for _ in xrange(10000000)]") print "Implicit: %.2f msec/pass" % (1000 * t.timeit(number=10)/10 )
Npmax: 8.78 msec/pass Explicit: 290.01 msec/pass Implicit: 790.27 msec/pass
Поиск максимального значения в списке на Python
В этой статье мы научимся находить максимальное значение в списке на Python. Для всестороннего понимания вопроса мы рассмотрим использование некоторых встроенных функций, простые подходы, а также небольшие реализации известных алгоритмов.
Сначала давайте вкратце рассмотрим, что такое список в Python и как найти в нем максимальное значение или просто наибольшее число.
Список в Python
В Python есть встроенный тип данных под названием список (list). По своей сути он сильно напоминает массив. Но в отличие от последнего данные внутри списка могут быть любого типа (необязательно одного): он может содержать целые числа, строки или значения с плавающей точкой, или даже другие списки.
Хранимые в списке данные определяются как разделенные запятыми значения, заключенные в квадратные скобки. Списки можно определять, используя любое имя переменной, а затем присваивая ей различные значения в квадратных скобках. Он является упорядоченным, изменяемым и допускает дублирование значений. Например:
list1 = ["Виктор", "Артем", "Роман"] list2 = [16, 78, 32, 67] list3 = ["яблоко", "манго", 16, "вишня", 3.4]Далее мы рассмотрим возможные варианты кода на Python, реализующего поиск наибольшего элемента в списке, состоящем из сравниваемых элементов. В наших примерах будут использоваться следующие методы/функции:
- Встроенная функция max()
- Метод грубой силы (перебора)
- Функция reduce()
- Алгоритм Heap Queue (очередь с приоритетом)
- Функция sort()
- Функция sorted()
- Метод хвостовой рекурсии
№1 Нахождение максимального значения с помощью функции max()
Это самый простой и понятный подход к поиску наибольшего элемента. Функция Python max() возвращает самый большой элемент итерабельного объекта. Ее также можно использовать для поиска максимального значения между двумя или более параметрами.
В приведенном ниже примере список передается функции max в качестве аргумента.
5 Ways to Find the list max index in Python
A list is a data structure in python which is used to store items of multiple data types. Because of that, it is considered to be one of the most versatile data structures. We can store items such as string, integer, float, set, list, etc., inside a given list. A list in python is a mutable data type, which means that even after creating a list its elements can be changed. A list is represented by storing its items inside square brackets ‘[ ]’. We can access list elements using indexing. In this article, we shall be looking into how in a python list, we can find the max index.
1. Finding max index using for loop
Finding the maximum index using a for loop is the most basic approach.
my_list = [10,72,54,25,90,40] max = my_list[0] index = 0 for i in range(1,len(my_list)): if my_list[i] > max: max = my_list[i] index = i print(f'Max index is : ')Here, we have taken a list named ‘my_list’, which contains a list of integers. We initially take the first element of the list as the maximum element and store the element into ‘max’. Then we take a variable as ‘index’ and store it with the value 0.
After that, we shall iterate a loop from index 1 to the last element of the list. Inside the loop using an if statement, we shall compare the ith element, i.e., the current element of ‘my_list’ with the ‘max’ variable. If the value of the current element happens to be greater than the value of ‘max’, then we shall assign the value of the current element to ‘max’ and the current index to ‘i’. After completion of the for loop, we shall print the value of ‘index’, which will denote the index of the maximum value from the list.
The output is:
An above method is a naive approach. It is for understanding how the maximum element will be found. There are more compact methods, and now we shall be looking into some of them.
2. Using built in methods – max() and index()
We can use python’s inbuilt methods to find the maximum index out of a python list.
The max() method is used to find the maximum value when a sequence of elements is given. It returns that maximum element as the function output. It accepts the sequence as the function argument.
The index() method is used to find the index of a given element from a python list. It accepts the element as an argument and returns the index of that element. In the case of multiple occurrences, it will return the smallest index of that element.
First, we shall use the max() function to find the maximum element from the given list ‘my_list’ and store it in ‘max_item’. Then using the index() function, we shall pass the ‘max_item’ inside the function. Using my_list.index(), we shall return the index of the maximum element and print that.
my_list = [10,72,54,25,90,40] max_item = max(my_list) print(f'Max index is : ')The output is:
3. Using enumerate() function to find Python list max index
The enumerate() function in python is used to add a counter to an iterable. With the help of enumerate() function, we can find the index of the maximum elements from a list. We shall use list comprehension for storing the index. List comprehension is a way of creating sequences out of already existing sequences.
my_list = [10,72,54,25,90,40] max_item = max(my_list) print([index for index, item in enumerate(my_list) if item == max_item])Using the max() function, we shall store the value of the maximum element into ‘max_item’. Then, we shall enumerate over my_list and check for which list item the value equals max_item. The index for that element shall be printed as a list item.
The output is:
4. Finding max index for multiple occurrences of elements
If there are multiple occurrences of the maximum element for a list, then we will have to apply a different logic for the same. We will make use of list comprehension to store multiple indexes inside a list.
my_list = [10,72,90,90,54,25,90,40] max_item = max(my_list) index_list = [index for index in range(len(my_list)) if my_list[index] == max_item] print(index_list)First, using the max() function, we shall find the maximum element from the list. Then, using list comprehension, we shall iterate over the list ‘my_list’, and whenever the item value equals the ‘max_item’, we shall save that index into ‘my_list’. Then, we shall print the ‘index_list’.
The output is:
5. Maximum index from a numpy array
To find the maximum item index using the numpy library. First, we shall import the numpy library. Then, using the array() function, we shall pass the list my_list as an argument inside the numpy array. This shall convert the given list into a numpy array and store it into ‘n’. Then, using the argmax() function, we shall print the index of the maximum item from the numpy array.
import numpy as np my_list = [10,72,54,25,90,40] n = np.array(my_list) print(f'Max index is : ')The output is:
That wraps up Python List Max Index. If you have any doubts or any thoughts to share, leave them in the comments below.
Until next time, Keep Learning!
Python: как найти индекс максимального значения в списке
Вы можете использовать следующий синтаксис, чтобы найти индекс максимального значения списка в Python:
#find max value in list max_value = max(list_name) #find index of max value in list max_index = list_name. index (max_value)
В следующих примерах показано, как использовать этот синтаксис на практике.
Пример 1: поиск индекса максимального значения в списке
Следующий код показывает, как найти максимальное значение в списке вместе с индексом максимального значения:
#define list of numbers x = [9, 3, 22, 7, 15, 16, 8, 8, 5, 2] #find max value in list max_value = max(x) #find index of max value in list max_index = x. index (max_value) #display max value print(max_value) 22 #display index of max value print(max_index) 2
Максимальное значение в списке равно 22 , и мы видим, что оно расположено в списке со значением индекса 2 .
Примечание. В Python значения индекса начинаются с 0.
Пример 2: поиск индекса максимального значения в списке со связями
В следующем коде показано, как найти максимальное значение в списке вместе с индексом максимального значения, когда имеется несколько максимальных значений.
#define list of numbers with multiple max values x = [9, 3, 22, 7, 15, 16, 8, 8, 5, 22] #find max value in list max_value = max(x) #find indices of max values in list indices = [index for index, val in enumerate(x) if val == max_value] #display max value print(max_value) 22 #display indices of max value print(indices) [2, 9]
Максимальное значение в списке равно 22 , и мы видим, что оно встречается при значениях индекса 2 и 9 в списке.