10

我有三个由相同数量的元素组成的列表:

a = [0.3, 1.5, 0.2, 2.6]
b = [1, 2, 3, 4]
c = [0.01, 0.02, 0.03, 0.04]

我需要根据 list 中的递减值同时对这三个列表进行排序a。这意味着我必须根据排序aa也需要排序。输出应如下所示:

a_s = [2.6, 1.5, 0.3, 0.2]
b_s = [4, 2, 1, 3]
c_s = [0.04, 0.02, 0.01, 0.03]

这种方式a_s现在简单地通过递减值排序,b_sc_s根据这种排序更改其项目位置。

4

1 回答 1

17

简短的回答

a_s, b_s, c_s = map(list, zip(*sorted(zip(a, b, c), reverse=True)))

长答案

首先,您必须压缩三个列表,创建一个项目列表:

>>> a = [0.3, 1.5, 0.2, 2.6]
>>> b = [1, 2, 3, 4]
>>> c = [0.01, 0.02, 0.03, 0.04]
>>> z = zip(a, b, c)
>>> z
[(0.3, 1, 0.01), (1.5, 2, 0.02), (0.2, 3, 0.03), (2.6, 4, 0.04)]

然后,您对该列表进行排序。元组列表按它们的第一个元素排序(当第一个元素相等时,使用第二个元素,依此类推):

>>> zs = sorted(z, reverse=True)
>>> zs
[(2.6, 4, 0.04), (1.5, 2, 0.02), (0.3, 1, 0.01), (0.2, 3, 0.03)]

Then you "unzip" the list. Unzipping is the same as calling zip with each tuple as argument, which is achieved by using the star syntax:

>>> u = zip(*zs)
>>> u
[(2.6, 1.5, 0.3, 0.2), (4, 2, 1, 3), (0.04, 0.02, 0.01, 0.03)]

You get a list of tuples, but you want lists. So, you map the list constructor over these items:

>>> u
[(2.6, 1.5, 0.3, 0.2), (4, 2, 1, 3), (0.04, 0.02, 0.01, 0.03)]
>>> map(list, u)
[[2.6, 1.5, 0.3, 0.2], [4, 2, 1, 3], [0.04, 0.02, 0.01, 0.03]]

You can then unpack the list into variables:

>>> a_s, b_s, c_s = map(list, u)

Observations

When sorting, you can explicitly indicate which item will be used for sorting, instead of relying on tuple's default ordering:

>>> from operator import itemgetter
>>> sorted(z, key=itemgetter(1))  # Sort by second item
[(0.3, 1, 0.01), (1.5, 2, 0.02), (0.2, 3, 0.03), (2.6, 4, 0.04)]
>>> sorted(z, key=itemgetter(2))  # Sort by third item
[(0.3, 1, 0.01), (1.5, 2, 0.02), (0.2, 3, 0.03), (2.6, 4, 0.04)]
于 2013-11-12T14:36:48.720 回答