【发布时间】:2012-09-14 00:12:43
【问题描述】:
期望的输出
我想要一个函数返回一个列表,如果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)
那么,我怎样才能更简洁地写这个?是否有清晰的列表理解解决方案?
【问题讨论】:
-
请注意,这与
sorted(range(len(l)), key=lambda i: l[i])不同...(虽然这是我的第一个想法。) -
@nightcracker 我知道,你的回答也是我的第一次尝试,所以我想我会发表评论让其他人知道这种方法是行不通的。
标签: python