根据其他列表中的值排序列表?

问题:

我有一个这样的字符串列表:

X = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]
Y = [ 0,   1,   1,    0,   1,   2,   2,   0,   1]

使用Y中的值排序X的最短方式是获取以下输出?

    ["a", "d", "h", "b", "c", "e", "i", "f", "g"]

具有相同“键”的元件的顺序并不重要。我可以使用for结构,但如果有较短的方法,我很好奇。有什么建议么?

回答:

 最短代码

[x for _,x in sorted(zip(Y,X))]

 例:

X = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]
Y = [ 0,   1,   1,    0,   1,   2,   2,   0,   1]

Z = [x for _,x in sorted(zip(Y,X))]
print(Z)  # ["a", "d", "h", "b", "c", "e", "i", "f", "g"]

 一般来说

[x for _, x in sorted(zip(Y,X), key=lambda pair: pair[0])]

 解释:

  1.  zip两个list
  2. 使用sorted()基于zip创建一个新的,排序的list
  3. 使用列表解析extract从排序的,压缩的list中的每对的第一个元素。

 For more information on how to set\use the key parameter as well as the sorted function in general, take a look at this.

 
 
Code问答: http://codewenda.com/topics/python/
Stackoverflow: Sorting list based on values from another list?

*转载请注明本文链接以及stackoverflow的英文链接

发表评论

电子邮件地址不会被公开。 必填项已用*标注

33 + = 41