使用列表上的 max()/min() 获取返回的最大或最小项的索引

发布于 2024-08-25 12:40:14 字数 537 浏览 7 评论 0 原文

我在列表上使用 Python 的 maxmin 函数来实现极小极大算法,并且我需要 max() 返回值的索引或min()。换句话说,我需要知道哪个动作产生了最大(在第一个玩家的回合)或最小(第二个玩家)值。

for i in range(9):
    new_board = current_board.new_board_with_move([i / 3, i % 3], player)

    if new_board:
        temp = min_max(new_board, depth + 1, not is_min_level)  
        values.append(temp)

if is_min_level:
    return min(values)
else:
    return max(values)

我需要能够返回最小值或最大值的实际索引,而不仅仅是值。

I'm using Python's max and min functions on lists for a minimax algorithm, and I need the index of the value returned by max() or min(). In other words, I need to know which move produced the max (at a first player's turn) or min (second player) value.

for i in range(9):
    new_board = current_board.new_board_with_move([i / 3, i % 3], player)

    if new_board:
        temp = min_max(new_board, depth + 1, not is_min_level)  
        values.append(temp)

if is_min_level:
    return min(values)
else:
    return max(values)

I need to be able to return the actual index of the min or max value, not just the value.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(22

盛夏尉蓝 2024-09-01 12:40:15

假设您有一个列表 values = [3,6,1,5],并且需要最小元素的索引,即本例中的 index_min = 2

避免使用其他答案中提出的 itemgetter() 解决方案,而是使用它,

index_min = min(range(len(values)), key=values.__getitem__)

因为它不需要 import 运算符 也不需要使用 enumerate ,并且它总是比使用 itemgetter() 的解决方案更快(基准如下)。

如果您正在处理 numpy 数组或可以负担 numpy 作为依赖项,请考虑使用

import numpy as np
index_min = np.argmin(values)

这将比第一个解决方案更快,即使您将其应用于纯 Python 列表,如果

  • :很少有元素(我的机器上大约有 2**4 个元素),
  • 您可以负担从纯列表到 numpy 数组的内存复制,

正如该基准测试所指出的:
输入图像描述这里

我已经使用 python 2.7 在我的机器上运行了上述两个解决方案的基准测试(蓝色:纯 python,第一个解决方案)(红色,numpy 解决方案)以及基于 itemgetter( )(黑色,参考溶液)。
与 python 3.5 相同的基准测试表明,这些方法与上面介绍的 python 2.7 情况完全相同

Say that you have a list values = [3,6,1,5], and need the index of the smallest element, i.e. index_min = 2 in this case.

Avoid the solution with itemgetter() presented in the other answers, and use instead

index_min = min(range(len(values)), key=values.__getitem__)

because it doesn't require to import operator nor to use enumerate, and it is always faster(benchmark below) than a solution using itemgetter().

If you are dealing with numpy arrays or can afford numpy as a dependency, consider also using

import numpy as np
index_min = np.argmin(values)

This will be faster than the first solution even if you apply it to a pure Python list if:

  • it is larger than a few elements (about 2**4 elements on my machine)
  • you can afford the memory copy from a pure list to a numpy array

as this benchmark points out:
enter image description here

I have run the benchmark on my machine with python 2.7 for the two solutions above (blue: pure python, first solution) (red, numpy solution) and for the standard solution based on itemgetter() (black, reference solution).
The same benchmark with python 3.5 showed that the methods compare exactly the same of the python 2.7 case presented above

海拔太高太耀眼 2024-09-01 12:40:15

使用 min() 查找最小值然后使用 .index()

values.index(min(values))

或最大值:

values.index(max(values))

如果您的列表包含重复的最小值或最大值,这将返回第一个值的索引。

Find the minimum value with min() then find that value's index with .index():

values.index(min(values))

Or the maximum:

values.index(max(values))

If your list contains repeats of the minimum or maximum value this will return the index of the first one.

强者自强 2024-09-01 12:40:15

如果枚举列表中的项目,则可以同时找到最小/最大索引和值,但对列表的原始值执行最小/最大。像这样:

import operator
min_index, min_value = min(enumerate(values), key=operator.itemgetter(1))
max_index, max_value = max(enumerate(values), key=operator.itemgetter(1))

这样列表只会在最小(或最大)内被遍历一次。

You can find the min/max index and value at the same time if you enumerate the items in the list, but perform min/max on the original values of the list. Like so:

import operator
min_index, min_value = min(enumerate(values), key=operator.itemgetter(1))
max_index, max_value = max(enumerate(values), key=operator.itemgetter(1))

This way the list will only be traversed once for min (or max).

夢归不見 2024-09-01 12:40:15

使用 NumPy 的 np.argmin()np.argmax() 功能:

import numpy as np
ind = np.argmax(mylist)

Use NumPy's np.argmin() or np.argmax() functions:

import numpy as np
ind = np.argmax(mylist)
缱绻入梦 2024-09-01 12:40:15

将值数组转换为(值,索引)对数组,并取其中的最大值/最小值。这将返回具有最大/最小值的最大/最小索引(即通过首先比较值,然后如果值相同则比较索引来比较对)。

values = [3, 5, 4, 5]
m, i = max((v, i) for i, v in enumerate(values))
print((m, i))  # (5, 3)

Turn the array of values into an array of (value,index)-pairs, and take the max/min of that. This returns the largest/smallest index that has the max/min (i.e. pairs are compared by first comparing the value, and then comparing the index if the values are the same).

values = [3, 5, 4, 5]
m, i = max((v, i) for i, v in enumerate(values))
print((m, i))  # (5, 3)
雪落纷纷 2024-09-01 12:40:15

我在 Python 3.11 上使用 perfplot (我的一个宠物项目)对主要答案进行了基准测试,结果证明

values.index(min(values))

是最快(越低越好):

在此处输入图像描述

除非您的数组已经是 numpy 数组。


生成绘图的代码:

import numpy as np
import operator
import perfplot


def min_enumerate(a):
    return min(enumerate(a), key=lambda x: x[1])[0]

def min_enumerate_itemgetter(a):
    min_index, min_value = min(enumerate(a), key=operator.itemgetter(1))
    return min_index

def getitem(a):
    return min(range(len(a)), key=a.__getitem__)

def np_argmin(a):
    return np.argmin(a)

def index_min(a):
    return a.index(min(a))


b = perfplot.bench(
    setup=lambda n: np.random.rand(n).tolist(),
    kernels=[
        min_enumerate,
        min_enumerate_itemgetter,
        getitem,
        np_argmin,
        index_min,
    ],
    labels = [
        "key=lambda x: x[1]",
        "key=itemgetter(1)",
        "key=.__getitem__",
        "np.argmin()",
        ".index()"
    ],
    xlabel="len(list)",
    n_range=[2**k for k in range(20)],
)
b.show()

I benchmarked the main answers using perfplot (a pet project of mine) on Python 3.11 and it turns out that

values.index(min(values))

is the fastest (lower is better):

enter image description here

unless your array is already a numpy array.


Code for generating the plot:

import numpy as np
import operator
import perfplot


def min_enumerate(a):
    return min(enumerate(a), key=lambda x: x[1])[0]

def min_enumerate_itemgetter(a):
    min_index, min_value = min(enumerate(a), key=operator.itemgetter(1))
    return min_index

def getitem(a):
    return min(range(len(a)), key=a.__getitem__)

def np_argmin(a):
    return np.argmin(a)

def index_min(a):
    return a.index(min(a))


b = perfplot.bench(
    setup=lambda n: np.random.rand(n).tolist(),
    kernels=[
        min_enumerate,
        min_enumerate_itemgetter,
        getitem,
        np_argmin,
        index_min,
    ],
    labels = [
        "key=lambda x: x[1]",
        "key=itemgetter(1)",
        "key=.__getitem__",
        "np.argmin()",
        ".index()"
    ],
    xlabel="len(list)",
    n_range=[2**k for k in range(20)],
)
b.show()
乖乖公主 2024-09-01 12:40:15

有两个答案(12),包括基准测试,但由于某种原因,它们都没有将 list.index() 包含到其基准测试中,即使在发布的已接受答案中建议了这一点至少在这些答案之前 2 年。

list.index() 是此页面上给出的最快选项,包括 enumerate (涉及它的所有版本), __getitem__numpy.argmin

此外,如果列表具有非唯一的最小值,并且您想要获取出现最小值的所有索引,则 while 循环中的 list.index 优于其他选项,例如 numpy 和 也枚举。请注意,您可以通过传递起点(这是 list.index 的第二个参数)来限制其搜索从特定索引开始,这对于性能至关重要,因为我们不想搜索从 while 循环的每次迭代开始。

# get the index of the minimum value
my_list = [1, 2, 0, 1]
idxmin = my_list.index(min(my_list))
print(idxmin)   # 2


# get all indices where the min value occurs
my_list = [1, 2, 3, 1]
idxmins = []
min_val = min(my_list)
pos = -1
while True:
    try:
        pos = my_list.index(min_val, pos+1)
        #                            ^^^^^   <---- pick up where we left off in the previous iteration
        idxmins.append(pos)
    except ValueError:
        break

print(idxmins)   # [0, 3]

以下基准测试(在 Python 3.11.4 和 numpy 1.25.2 上执行)表明,无论列表长度如何,list.index 的速度几乎是所有其他选项的两倍。左图还显示,对于长列表,getitem 的执行效果与 enumerate(和 numpy.argmin)相同,这表明 gg349Nico 的基准测试已经过时了。

右图显示,如果最小值不唯一,并且我们想要找到最小值的所有索引,则如上所述的 while 循环中的 list.index 的性能比竞争选项要好得多涉及 enumerate 或 numpy,特别是对于长列表。

benchmark

用于生成上图的代码:

from operator import itemgetter
import numpy as np
import matplotlib.pyplot as plt
import perfplot


def enumerate_1(a):
    return min(enumerate(a), key=itemgetter(1))[0]


def np_argmin_1(a):
    return np.argmin(a)


def getitem(a):
    return min(range(len(a)), key=a.__getitem__)


def list_index_1(a):
    return a.index(min(a))


def enumerate_2(a):
    min_val = min(a)
    return [i for i, v in enumerate(a) if v == min_val]


def np_argmin_2(a):
    arr = np.array(a)
    return np.arange(len(a))[arr==arr.min()]


def list_index_2(a):
    result = []
    min_val = min(a)
    pos = -1
    while True:
        try:
            pos = a.index(min_val, pos+1)
            result.append(pos)
        except ValueError:
            break
    return result


kernels_list = [[enumerate_1, list_index_1, np_argmin_1, getitem], 
                [enumerate_2, list_index_2, np_argmin_2]]
n_range = [2**k for k in range(1, 20)]
su = lambda n: list(range(n, 0, -1))
titles = ['Get index of a unique min value', 
          'Get indices of a non-unique min value']
labels = ['enumerate', 'list_index', 'np_argmin', 'getitem']
xlabel = 'List length'


fig, axs = plt.subplots(1, 2, figsize=(12, 5), facecolor='white', dpi=60)
for ax, ks, t in zip(axs, kernels_list, titles):
    plt.sca(ax)
    perfplot.plot(ks, n_range, su, None, labels, xlabel, t, relative_to=1)
    ax.xaxis.set_tick_params(labelsize=13)
plt.setp(axs, ylim=(0, 5), yticks=range(1, 6), 
         xlim=(1, 1100000), xscale='log', xticks=[1, 100, 10000, 1000000]);
fig.tight_layout();
fig.savefig('benchmark.png', dpi=60);

There are two answers (1, 2) that include benchmark but for some reason, neither of them include list.index() into their benchmark, even though it was suggested in the accepted answer that was posted at least 2 years before these answers.

list.index() is the fastest option given on this page, including enumerate (all versions that involve it), __getitem__ and numpy.argmin.

Moreover, if the list has a non-unique minimum value and you want to get all indices where the minimum value occurs, list.index in a while-loop outperforms other options such as numpy and enumerate as well. Note that you can limit its search to begin from a particular index by passing the starting point (which is the second argument to list.index), which is crucial for performance because we don't want to search from the beginning in every iteration of the while-loop.

# get the index of the minimum value
my_list = [1, 2, 0, 1]
idxmin = my_list.index(min(my_list))
print(idxmin)   # 2


# get all indices where the min value occurs
my_list = [1, 2, 3, 1]
idxmins = []
min_val = min(my_list)
pos = -1
while True:
    try:
        pos = my_list.index(min_val, pos+1)
        #                            ^^^^^   <---- pick up where we left off in the previous iteration
        idxmins.append(pos)
    except ValueError:
        break

print(idxmins)   # [0, 3]

The following benchmarks (performed on Python 3.11.4 and numpy 1.25.2) show that list.index is almost twice as fast as all other options no matter the length of the list. The left graph also shows that getitem performs the same as enumerate (and numpy.argmin) for long lists, which shows that gg349 and Nico's benchmarks are outdated.

The right graph shows that if the minimum value is non-unique and we want to find all indices of the minimum value, then list.index in a while loop as outlined above performs so much better than competing options involving enumerate or numpy, especially for long lists.

benchmark

The code used to produce the figure above:

from operator import itemgetter
import numpy as np
import matplotlib.pyplot as plt
import perfplot


def enumerate_1(a):
    return min(enumerate(a), key=itemgetter(1))[0]


def np_argmin_1(a):
    return np.argmin(a)


def getitem(a):
    return min(range(len(a)), key=a.__getitem__)


def list_index_1(a):
    return a.index(min(a))


def enumerate_2(a):
    min_val = min(a)
    return [i for i, v in enumerate(a) if v == min_val]


def np_argmin_2(a):
    arr = np.array(a)
    return np.arange(len(a))[arr==arr.min()]


def list_index_2(a):
    result = []
    min_val = min(a)
    pos = -1
    while True:
        try:
            pos = a.index(min_val, pos+1)
            result.append(pos)
        except ValueError:
            break
    return result


kernels_list = [[enumerate_1, list_index_1, np_argmin_1, getitem], 
                [enumerate_2, list_index_2, np_argmin_2]]
n_range = [2**k for k in range(1, 20)]
su = lambda n: list(range(n, 0, -1))
titles = ['Get index of a unique min value', 
          'Get indices of a non-unique min value']
labels = ['enumerate', 'list_index', 'np_argmin', 'getitem']
xlabel = 'List length'


fig, axs = plt.subplots(1, 2, figsize=(12, 5), facecolor='white', dpi=60)
for ax, ks, t in zip(axs, kernels_list, titles):
    plt.sca(ax)
    perfplot.plot(ks, n_range, su, None, labels, xlabel, t, relative_to=1)
    ax.xaxis.set_tick_params(labelsize=13)
plt.setp(axs, ylim=(0, 5), yticks=range(1, 6), 
         xlim=(1, 1100000), xscale='log', xticks=[1, 100, 10000, 1000000]);
fig.tight_layout();
fig.savefig('benchmark.png', dpi=60);
旧情勿念 2024-09-01 12:40:15

如果您需要最小值的所有索引(因为最小值可能会在列表中出现多次):

minval = min(mylist)
ind = [i for i, v in enumerate(mylist) if v == minval]

If you need all the indexes of the minimum (because the minimum might appear more than once in the list):

minval = min(mylist)
ind = [i for i, v in enumerate(mylist) if v == minval]
青丝拂面 2024-09-01 12:40:15

获得最大值后,试试这个:

max_val = max(list)
index_max = list.index(max_val)

比很多选项简单得多。

After you get the maximum values, try this:

max_val = max(list)
index_max = list.index(max_val)

Much simpler than a lot of options.

猫弦 2024-09-01 12:40:15

这可以使用内置的 enumerate() max() 函数以及 max() 函数的可选 key= 参数和一个简单的 lambda< /code> 表达式:

values = [1, 5, 10]
max_index, max_value = max(enumerate(values), key=lambda v: v[1])
# => (2, 10)

max() 它表示 key= 参数需要一个类似于 list.sort() 函数。另请参阅排序方法

min() 的工作原理相同。顺便说一句,它返回第一个最大/最小值。

This is possible using the built-in enumerate() and max() functions and the optional key= argument of the max() function and a simple lambda expression:

values = [1, 5, 10]
max_index, max_value = max(enumerate(values), key=lambda v: v[1])
# => (2, 10)

In the docs for max() it says that the key= argument expects a function like in the list.sort() function. Also see the Sorting HOW TO.

It works the same for min(). Btw, it returns the first max/min value.

桜花祭 2024-09-01 12:40:15

Pandas 现在有了一个更温和的解决方案,尝试一下:

df[column].idxmax()

Pandas has now got a much more gentle solution, try it:

df[column].idxmax()

泼猴你往哪里跑 2024-09-01 12:40:15

使用 numpy 数组和 argmax() 函数

a = np.array([1, 2, 3])
b = np.argmax(a)
print(b)  # 2

Use a numpy array and the argmax() function

a = np.array([1, 2, 3])
b = np.argmax(a)
print(b)  # 2
清欢 2024-09-01 12:40:15

使用numpy模块的函数numpy.where

import numpy as n
x = n.array((3,3,4,7,4,56,65,1))

对于最小值的索引:

idx = n.where(x==x.min())[0]

对于最大值的索引:

idx = n.where(x==x.max())[0]

事实上,这个函数要强大得多。你可以提出各种布尔运算
对于 3 到 60 之间的索引值:

idx = n.where((x>3)&(x<60))[0]
idx
array([2, 3, 4, 5])
x[idx]
array([ 4,  7,  4, 56])

Use numpy module's function numpy.where

import numpy as n
x = n.array((3,3,4,7,4,56,65,1))

For index of minimum value:

idx = n.where(x==x.min())[0]

For index of maximum value:

idx = n.where(x==x.max())[0]

In fact, this function is much more powerful. You can pose all kinds of boolean operations
For index of value between 3 and 60:

idx = n.where((x>3)&(x<60))[0]
idx
array([2, 3, 4, 5])
x[idx]
array([ 4,  7,  4, 56])
终止放荡 2024-09-01 12:40:15

假设您有一个列表,例如:

a = [9,8,7]

以下两种方法是获取具有最小元素及其索引的元组的非常紧凑的方法。两者的处理时间相似。我更喜欢拉链方法,但这就是我的口味。

zip 方法

element, index = min(list(zip(a, range(len(a)))))

min(list(zip(a, range(len(a)))))
(7, 2)

timeit min(list(zip(a, range(len(a)))))
1.36 µs ± 107 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

枚举方法

index, element = min(list(enumerate(a)), key=lambda x:x[1])

min(list(enumerate(a)), key=lambda x:x[1])
(2, 7)

timeit min(list(enumerate(a)), key=lambda x:x[1])
1.45 µs ± 78.1 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

Say you have a list such as:

a = [9,8,7]

The following two methods are pretty compact ways to get a tuple with the minimum element and its index. Both take a similar time to process. I better like the zip method, but that is my taste.

zip method

element, index = min(list(zip(a, range(len(a)))))

min(list(zip(a, range(len(a)))))
(7, 2)

timeit min(list(zip(a, range(len(a)))))
1.36 µs ± 107 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

enumerate method

index, element = min(list(enumerate(a)), key=lambda x:x[1])

min(list(enumerate(a)), key=lambda x:x[1])
(2, 7)

timeit min(list(enumerate(a)), key=lambda x:x[1])
1.45 µs ± 78.1 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
心头的小情儿 2024-09-01 12:40:15

您可以将 lambda 作为 key= 参数传递给 max()/分钟()

max_index = max(range(len(my_list)), key=lambda index: my_list[index])

You can pass a lambda as the key= argument to max()/min():

max_index = max(range(len(my_list)), key=lambda index: my_list[index])
゛清羽墨安 2024-09-01 12:40:15

为什么要麻烦先添加索引然后再反转它们呢? Enumerate() 函数只是 zip() 函数用法的一个特例。让我们以适当的方式使用它:

my_indexed_list = zip(my_list, range(len(my_list)))

min_value, min_index = min(my_indexed_list)
max_value, max_index = max(my_indexed_list)

Why bother to add indices first and then reverse them? Enumerate() function is just a special case of zip() function usage. Let's use it in appropiate way:

my_indexed_list = zip(my_list, range(len(my_list)))

min_value, min_index = min(my_indexed_list)
max_value, max_index = max(my_indexed_list)
嘿看小鸭子会跑 2024-09-01 12:40:15

就这么简单:

stuff = [2, 4, 8, 15, 11]

index = stuff.index(max(stuff))

Simple as that :

stuff = [2, 4, 8, 15, 11]

index = stuff.index(max(stuff))
淡看悲欢离合 2024-09-01 12:40:15

假设您有以下列表 my_list = [1,2,3,4,5,6,7,8,9,10] 并且我们知道如果我们执行 max(my_list) 它将返回 10min(my_list) 将返回 1。现在我们想要获取最大或最小元素的索引,我们可以执行以下操作。

my_list = [1,2,3,4,5,6,7,8,9,10]

max_value = max(my_list) # returns 10
max_value_index = my_list.index(max_value) # retuns 9

#to get an index of minimum value

min_value = min(my_list) # returns 1
min_value_index = my_list.index(min_value) # retuns 0

Assuming you have a following list my_list = [1,2,3,4,5,6,7,8,9,10] and we know that if we do max(my_list) it will return 10 and min(my_list) will return 1. Now we want to get the index of the maximum or minimum element we can do the following.

my_list = [1,2,3,4,5,6,7,8,9,10]

max_value = max(my_list) # returns 10
max_value_index = my_list.index(max_value) # retuns 9

#to get an index of minimum value

min_value = min(my_list) # returns 1
min_value_index = my_list.index(min_value) # retuns 0

望笑 2024-09-01 12:40:15

https://docs.python.org/3/library/functions.html# max

如果多个项目都最大,则该函数返回遇到的第一个。这与其他排序稳定性保持工具一致,例如 sorted(iterable, key=keyfunc, reverse=True)[0]

要获取不仅仅是第一个遇到的内容,请使用 sort 方法。

import operator

x = [2, 5, 7, 4, 8, 2, 6, 1, 7, 1, 8, 3, 4, 9, 3, 6, 5, 0, 9, 0]

min = False
max = True

min_val_index = sorted( list(zip(x, range(len(x)))), key = operator.itemgetter(0), reverse = min )

max_val_index = sorted( list(zip(x, range(len(x)))), key = operator.itemgetter(0), reverse = max )


min_val_index[0]
>(0, 17)

max_val_index[0]
>(9, 13)

import ittertools

max_val = max_val_index[0][0]

maxes = [n for n in itertools.takewhile(lambda x: x[0] == max_val, max_val_index)]

https://docs.python.org/3/library/functions.html#max

If multiple items are maximal, the function returns the first one encountered. This is consistent with other sort-stability preserving tools such as sorted(iterable, key=keyfunc, reverse=True)[0]

To get more than just the first encountered, use the sort method.

import operator

x = [2, 5, 7, 4, 8, 2, 6, 1, 7, 1, 8, 3, 4, 9, 3, 6, 5, 0, 9, 0]

min = False
max = True

min_val_index = sorted( list(zip(x, range(len(x)))), key = operator.itemgetter(0), reverse = min )

max_val_index = sorted( list(zip(x, range(len(x)))), key = operator.itemgetter(0), reverse = max )


min_val_index[0]
>(0, 17)

max_val_index[0]
>(9, 13)

import ittertools

max_val = max_val_index[0][0]

maxes = [n for n in itertools.takewhile(lambda x: x[0] == max_val, max_val_index)]
十雾 2024-09-01 12:40:15

只是对已经说过的内容进行一点小小的补充。
values.index(min(values)) 似乎返回 min 的最小索引。以下获取最大索引:

    values.reverse()
    (values.index(min(values)) + len(values) - 1) % len(values)
    values.reverse()

如果原地反转的副作用不重要,则可以省略最后一行。

迭代所有发生的情况

    indices = []
    i = -1
    for _ in range(values.count(min(values))):
      i = values[i + 1:].index(min(values)) + i + 1
      indices.append(i)

为了简洁起见, 。在循环外部缓存 min(values),values.count(min) 可能是一个更好的主意。

Just a minor addition to what has already been said.
values.index(min(values)) seems to return the smallest index of min. The following gets the largest index:

    values.reverse()
    (values.index(min(values)) + len(values) - 1) % len(values)
    values.reverse()

The last line can be left out if the side effect of reversing in place does not matter.

To iterate through all occurrences

    indices = []
    i = -1
    for _ in range(values.count(min(values))):
      i = values[i + 1:].index(min(values)) + i + 1
      indices.append(i)

For the sake of brevity. It is probably a better idea to cache min(values), values.count(min) outside the loop.

美煞众生 2024-09-01 12:40:15

如果您不想导入其他模块,则可以使用一种简单的方法来查找列表中具有最小值的索引:

min_value = min(values)
indexes_with_min_value = [i for i in range(0,len(values)) if values[i] == min_value]

然后选择第一个模块:

choosen = indexes_with_min_value[0]

A simple way for finding the indexes with minimal value in a list if you don't want to import additional modules:

min_value = min(values)
indexes_with_min_value = [i for i in range(0,len(values)) if values[i] == min_value]

Then choose for example the first one:

choosen = indexes_with_min_value[0]
仲春光 2024-09-01 12:40:15

怎么样:

a=[1,55,2,36,35,34,98,0]
max_index=dict(zip(a,range(len(a))))[max(a)]

它从 a 中的项目作为键,将它们的索引作为值创建一个字典,因此 dict(zip(a,range(len(a))))[max( a)] 返回与键 max(a) 对应的值,它是 a 中最大值的索引。我是 python 的初学者,所以我不知道这个解决方案的计算复杂性。

What about this:

a=[1,55,2,36,35,34,98,0]
max_index=dict(zip(a,range(len(a))))[max(a)]

It creates a dictionary from the items in a as keys and their indexes as values, thus dict(zip(a,range(len(a))))[max(a)] returns the value that corresponds to the key max(a) which is the index of the maximum in a. I'm a beginner in python so I don't know about the computational complexity of this solution.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文