列表 A 和列表 B 具有相应的元素:
A = ['a','c','b']
B = [5,7,9]
如何对 A 中的元素进行排序(得到 A_sorted 如下),而 B 中的值不变(得到 B_sorted 如下)?
A_sorted = A.sort()
A_sorted = ['a','b','c']
B_sorted = [5,9,7]
A = ['a','c','b']
B = [5,7,4]
A_sorted, B_sorted = zip(*sorted(zip(A, B))
结果:
>>> A_sorted
('a', 'b', 'c')
>>> B_sorted
(5, 4, 7)
解释:
>>> step_1 = zip(A,B) # creates list of tuples using
# two original lists
# tuples will allow us to keep correspondence
# between A and B
>>> step_1
[('a', 5), ('c', 7), ('b', 4)]
>>> step_2 = sorted(step_1) # key step: the tuples are sorted by
# the first value.
>>> step_2
[('a', 5), ('b', 4), ('c', 7)]
>>> step_3 = zip(*step_2) # This is just a trick to get back the original
# "lists", however they are actually tuples
>>> step_3
[('a', 'b', 'c'), (5, 4, 7)]
一个 numpy 解决方案,因为问题已被标记。使用argsort
:
s = A.argsort()
A_sorted = A[s]
B_sorted = B[s]
这个怎么运作:
A = np.array(['a', 'c', 'b'])
B = np.array([5, 7, 9])
s = A.argsort() # returns the _indices_ that would sort A
print s
# array([0, 2, 1])
现在您可以使用或s
获取排序列表,按照排序的顺序:A
B
A
A[s]
# array(['a', 'b', 'c'],
# dtype='|S1')
B[s]
# array([5, 9, 7])
该list.sort()
函数不返回排序列表,而是对列表进行就地排序。因此,它将返回None
,因此您设置A_sorted
为None
。
您在这里有两个选择:
在你使用的sorted()
地方使用A.sort()
。这将对列表进行排序,但也会返回排序后的列表。
不要分配A.sort()
给任何东西。
所以我认为你正在寻找的是创建A_sorted
andB_sorted
而不修改A
and B
。然后在这里你会使用sorted()
:
A_sorted = sorted(A)
B_sorted = sorted(B)