gpt4 book ai didi

python - 给定一个 "jumbled"列表 L,得到一个列表,其中每个元素都是 L 对应元素的索引,如果 L 已排序

转载 作者:太空狗 更新时间:2023-10-30 01:45:00 26 4
gpt4 key购买 nike

期望的输出

我想要一个函数返回一个列表,这样,给定一个“困惑的”列表 l,每个元素都是 l 对应元素的索引,如果 l 已排序。 (抱歉,我想不出更简单的说法。)

示例

f([3,1,2]) = [2,0,1]

f([3,1,2,2,3]) = [3,0,1,2,4],因为排序的输入是 [1,2,2,3,3]

(这对一些统计计算很有用。)

我的尝试

我想出了一种方法来执行此功能,但这是 python - 似乎应该有一个单行代码来执行此操作,或者至少是一种更简洁、更清晰的方法。

def getIndiciesInSorted(l):
sortedL = sorted(l)
outputList = []
for num in l:
sortedIndex = sortedL.index(num)
outputList.append(sortedIndex)
sortedL[sortedIndex] = None
return outputList

l=[3,1,2,2,3]
print getIndiciesInSorted(l)

那么,我怎样才能写得更简洁呢?是否有清晰的列表理解解决方案?

最佳答案

def argsort(seq):
# http://stackoverflow.com/questions/3382352/3382369#3382369
# http://stackoverflow.com/questions/3071415/3071441#3071441
'''
>>> seq=[1,3,0,4,2]
>>> index=argsort(seq)
[2, 0, 4, 1, 3]

Given seq and the index, you can construct the sorted seq:
>>> sorted_seq=[seq[x] for x in index]
>>> assert sorted_seq == sorted(seq)

Given the sorted seq and the index, you can reconstruct seq:
>>> assert [sorted_seq[x] for x in argsort(index)] == seq
'''
return sorted(range(len(seq)), key=seq.__getitem__)

def f(seq):
idx = argsort(seq)
return argsort(idx)

print(f([3,1,2]))
# [2, 0, 1]

print(f([3,1,2,2,3]))
# [3, 0, 1, 2, 4]

注意 nightcracker 的函数速度更快:

def get_sorted_indices(l):
sorted_positions = sorted(range(len(l)), key=l.__getitem__)
result = [None for _ in range(len(l))]
for new_index, old_index in enumerate(sorted_positions):
result[old_index] = new_index
return result

对于长列表,差异可能很重要:

In [83]: import random
In [98]: l = [random.randrange(100) for _ in range(10000)]
In [104]: timeit get_sorted_indices(l)
100 loops, best of 3: 4.73 ms per loop

In [105]: timeit f(l)
100 loops, best of 3: 6.64 ms per loop

关于python - 给定一个 "jumbled"列表 L,得到一个列表,其中每个元素都是 L 对应元素的索引,如果 L 已排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12416537/

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