gpt4 book ai didi

python - 获取Python中列表的最小N个元素的索引

转载 作者:太空宇宙 更新时间:2023-11-03 12:32:30 38 4
gpt4 key购买 nike

我想获取列表中最少 N 个元素的索引。如果我能在另一个列表中获得该输出,那就太好了。

例如:

[1, 1, 10, 5, 3, 5]
output = [0, 1]

[10, 5, 12, 5, 0, 10]
output = [4]

[9, 2, 8, 2, 3, 4, 2]
output = [1, 3, 6]

[10, 10, 10, 10, 10, 10]
output = [0, 1, 2, 3, 4, 5]

我知道 .index 返回列表中最小值的第一个索引,但我不知道当它出现不止一次时如何返回最小值的所有索引。

最佳答案

>>> L = [9, 2, 8, 2, 3, 4, 2]
>>> minL = min(L)
>>> [i for i, x in enumerate(L) if x == minL]
[1, 3, 6]

目前,其他解决方案在迭代期间调用min,导致O(n^2) 复杂度较差且不必要。


Kasra 的编辑:原始解决方案的 n^2 复杂性的证据:

>>> L1000 = [randint(0, 100) for _ in xrange(1000)]
>>> L2000 = [randint(0, 100) for _ in xrange(2000)]
>>> L3000 = [randint(0, 100) for _ in xrange(3000)]
>>> L4000 = [randint(0, 100) for _ in xrange(4000)]
>>> L5000 = [randint(0, 100) for _ in xrange(5000)]
>>> timeit [i for i, x in enumerate(L1000) if x == min(L1000)]
10 loops, best of 3: 18.8 ms per loop
>>> timeit [i for i, x in enumerate(L2000) if x == min(L2000)]
10 loops, best of 3: 73.6 ms per loop
>>> timeit [i for i, x in enumerate(L3000) if x == min(L3000)]
1 loops, best of 3: 166 ms per loop
>>> timeit [i for i, x in enumerate(L4000) if x == min(L4000)]
1 loops, best of 3: 294 ms per loop
>>> timeit [i for i, x in enumerate(L5000) if x == min(L5000)]
1 loops, best of 3: 457 ms per loop

关于python - 获取Python中列表的最小N个元素的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29677673/

38 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com