根据另一个列表值对列表的索引值排序

2024-06-09 01:42:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我想根据另一个列表的值对一个列表的索引进行排序。我的代码是:

  x = ['mango','orange','butter','milk','coconut','tree','sky','moon','dog','cat','ant','pop','fog'] // sort this list
  y = ['1','10','11','12','13','2','3','4','5','6','7','8','9']

我要做的是:

  >>> x.sort(key=lambda (a,b): y.index(a))
      Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "<stdin>", line 1, in <lambda>
      ValueError: too many values to unpack

我期望的结果是:

   x = ['mango','cat','ant', 'pop', 'fog','orange','butter','milk','coconut','tree','sky','moon','dog']  

Tags: tree列表sortpopcatdogorangeant
2条回答

我想你的猫走了。你知道吗

>>> new = [x[int(index) - 1] for index in y]
>>> new
['mango', 'cat', 'ant', 'pop', 'fog', 'orange', 'butter', 'milk', 'coconut', 'tree', 'sky', 'moon', 'dog']

尝试将索引和项放在一起,排序并分开:

y = [int(index) for index in y]  # need to sort numerically, not alphabetically
x = [item for index, item in sorted(zip(y, x))]

这是正确排序的,因为元组是按第一个键(即索引)排序的,然后将项的正确顺序提取为这种排序的副产品。你知道吗

相关问题 更多 >