我有一个列表,它有一个出现多次的最小元素,比如
a = [1,2,1,1,4,5,6]我希望Python返回元素1和1所在的列表中的所有索引。我试着用
min_index, min_value = min(enumerate(a), key=operator.itemgetter(1))它只给出1最先出现的索引。
发布于 2013-02-27 04:31:59
确定最小元素,然后对照列表中的其他元素对其进行检查。
def locate_min(a):
    smallest = min(a)
    return smallest, [index for index, element in enumerate(a) 
                      if smallest == element]它将返回一个元组(min_element,location,location,...)。如果我没理解错的话,这就是我认为你想要的。对于您的示例:
>>> locate_min([1, 2, 1, 1, 4, 5, 6])
(1, [0, 2, 3])这个例子使用了列表理解。如果您不熟悉这一点,它大致相当于下面的for-loop版本。(使用第一个版本,这只是为了帮助您理解它的工作原理)
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_indicieshttps://stackoverflow.com/questions/15098642
复制相似问题