从列表中获取所有最小元素及其索引 [英] Getting all the min elements and its indices from a list
问题描述
我有一个列表,其中包含一个最小元素,该元素多次出现,例如
I have a list that has a minimum element that is present multiple times like
a = [1,2,1,1,4,5,6]
我想让Python返回元素1
和存在1
的列表中的所有索引.我尝试使用
And I want Python to return the element 1
and all the indices in the list where 1
is present. I tried using
min_index, min_value = min(enumerate(a), key=operator.itemgetter(1))
仅给出首先出现1
的索引.
which gives only the index where 1
occurs first.
推荐答案
确定最小元素,然后将其与列表中的其他元素进行比较.
determine the minimum element, and then check it against other elements in the list.
def locate_min(a):
smallest = min(a)
return smallest, [index for index, element in enumerate(a)
if smallest == element]
将返回一个元组(min_element,[位置,位置,...]).如果我理解正确,这就是我想要的.以您为例:
which will return a tuple (min_element, [location, location, ...]). If I understand you correctly, this is what I think you want. For you example:
>>> locate_min([1, 2, 1, 1, 4, 5, 6])
(1, [0, 2, 3])
此示例使用列表理解.如果您不熟悉此功能,则它大致等效于以下for循环版本. (使用第一个版本,这只是为了帮助您了解其工作原理)
This example uses a list comprehension. If you're not familiar with this, it's roughly equivalent to the following for-loop version. (use the first version, this is just to help your understanding of how it works)
def locate_min(a):
min_indicies = []
smallest = min(a)
for index, element in enumerate(a):
if smallest == element: # check if this element is the minimum_value
min_indicies.append(index) # add the index to the list if it is
return smallest, min_indicies
这篇关于从列表中获取所有最小元素及其索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!