我有一个 list :
[55, 41, 45, 43, 60, 47, 33, 70, 42, 42, 44]
我想创建一个新列表,按它们的顺序排列这些项目:
预期输出:
[7, ,2 ,9 ,10, 4, 11, 3, 6, 1, 5, 8]
尝试了这 3 个版本的 func 但它不能正常工作,不知道为什么?
def argsort(seq):
#return sorted(range(len(seq)), key = seq.__getitem__)
#return [i for (v, i) in sorted((v, i) for (i, v) in enumerate(seq))]
return [x for x,y in sorted(enumerate(seq), key = lambda x: x[1])]
返回:
[6, 1, 8, 9, 3, 10, 2, 5, 0, 4, 7]
最佳答案
让我们对您所追求的事物提出更精确的定义:
Given a list L of numbers, create a list M that contains the valid indices of L, such that
M[i]
is the index at which thei
th element of L occurs, when sorted. PresentM
as if the first element of L occurs at index 1.
现在,列表的有效索引有两种方式:
range(len(L))
: 给出一个数字序列 0... len(L)-1 enumerate(L)
: 给出一个元组序列 (0, L[0])... (len(L)-1, L[len(L)-1])
由于您想在列表索引从 1 开始(实际上它们在 python 中从 0 开始)的假设下操作,我们需要做一些偏移
range(len(L))
变成 `range(1, len(L)+1) enumerate(L)
变成 enumerate(L, 1)
(可选参数告诉 enumerate
从 1 开始编号) 由于我们也需要列表项,让我们使用
enumerate
,而不是使用 range
并进行查找(我个人更喜欢这种方法,尽管两者都有效)所以现在,我们可以得到一个元组列表,其中每个元组包含 L 中一个元素的索引和 L 中相应元素的索引。我们需要按元素本身对其进行排序。这可以通过调用
sorted
来完成,可选的 key
参数说明我们应该按元组的第二个元素排序( operator.itemgetter(1)
正是如此)。一旦我们有这样的元组的排序列表,我们需要做的就是提取每个元组的第一个元素(L 中的索引),我们可以使用列表理解
[i[0] for i in mylist]
,或等效的 [operator.itemgetter(0)(t) for t in mylist]
将所有这些元素放在一起,我们得到以下内容
In [138]: L = [55, 41, 45, 43, 60, 47, 33, 70, 42, 42, 44]
In [139]: [operator.itemgetter(0)(t) for t in sorted(enumerate(L,1), key=operator.itemgetter(1))]
Out[139]: [7, 2, 9, 10, 4, 11, 3, 6, 1, 5, 8]
关于python - 基础 Python : Rank items in list,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28086865/