我有两个列表列表,我想将第一个列表相对于第二个进行排序。例如这里我有两个
old = [[1, 7, 3, 2, 5, 4, 6, 0, 8, 9],
[7, 3, 2, 5, 4, 6, 1, 8, 0, 9],
[9, 2, 8, 7, 1, 5, 0, 4, 6, 3]]
new = [[4, 1, 5, 6, 7, 9, 10, 11, 8, 2, 3, 0],
[10, 6, 4, 3, 0, 11, 2, 5, 8, 1, 9, 7],
[0, 1, 7, 10, 9, 6, 4, 5, 8, 2, 3, 11]]
我想对new
列表列表进行排序old
。所以对于新的条目应该成为
sorted_new = [[1, 7, 3, 2, 5, 4, 6, 0, 8, 9, 10, 11],
[7, 3, 2, 5, 4, 6, 1, 8, 0, 9, 10, 11],
[9, 2, 8, 7, 1, 5, 0, 4, 6, 3, 10, 11]]
需要注意的是,要匹配的两个列表的大小不同。我怎样才能做到这一点?
您可以使用以下方法:
sorted_new = []
for sub_new,sub_old in zip(new,old):
old_idx = {k:v for v,k in enumerate(sub_old)}
sorted_new.append(sorted(sub_new,key=lambda x:old_idx.get(x,len(sub_old))))
然后生成:
>>> sorted_new
[[1, 7, 3, 2, 5, 4, 6, 0, 8, 9, 10, 11], [7, 3, 2, 5, 4, 6, 1, 8, 0, 9, 10, 11], [9, 2, 8, 7, 1, 5, 0, 4, 6, 3, 10, 11]]
该代码的工作原理如下:我们首先在两个列表上运行new
,并old
兼任。对于每对这样的列表。我们首先生成一个带有字典理解的字典,它将 的元素映射sub_old
到它们在列表中的相应索引。
接下来我们为 构造一个排序列表sub_new
。如果那个元素sub_new
在 中old_idx
,我们返回索引(这就是排序键)。如果不是,我们返回一个 default len(sub_old)
,因此它大于字典中的所有索引。结果,该元素将被放置在列表的右侧。
由于 Python 的 sort 函数保证稳定,这意味着不在 中的元素old
将保持原始顺序。
我们本可以在该list.index(..)
方法周围使用一些魔法,而不是构建这样的索引字典。但问题.index(..)
在于它在O(n) 中运行。因此,这将使每个子列表的算法为O(m×n log n),其中m是 中的元素数old
,n是 中的元素数new
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句