通过跟踪交换的索引对列表进行排序以重塑第二个列表

Sorting a list by keeping track of the swapped indices for reshaping a second list

我有一个包含数字的列表:

S = [12, 5, 7, 100, 50]

和一个关联列表列表:

AS = [['G'], ['W'], ['F'], ['N'], ['L']]

并且我想对 S 列表进行排序,以便关联列表也相应地进行修改。 输出:

SortedS = [5, 7, 12, 50, 100]
modifiedAS = [['W'], ['F'], ['G'], ['L'], ['N']]

有什么帮助吗?

Z = [x for _,x in sorted(zip(S,AS))]

我们走了。 Z 将是您按 S 列表的排序排序的 AS 列表

S = [12, 5, 7, 100, 50]
AS = [['G'], ['W'], ['F'], ['N'], ['L']]

zipped_sorted_lists = sorted(zip(S, AS), key=lambda i: i[0])
S_sorted, AS_sorted = zip(*zipped_sorted_lists)

print(S_sorted)
print(AS_sorted)

控制台输出:

(5, 7, 12, 50, 100)
(['W'], ['F'], ['G'], ['L'], ['N'])