例如有三个列表:
unsorted_key = ['q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p']
sorted_key = ['e', 'i', 'o', 'p', 'q', 'r', 't', 'u', 'w', 'y']
ciphertext = [
['u', 't', 'x', 'e'],
['p', 'r', 'k', 'p'],
['v', 'n', 'x', 'a'],
['n', 'h', 'e', 'x'],
['x', 'h', 'm', 's'],
['l', 'x', 'c', 'x'],
['x', 'c', 'y', 'a'],
['t', 'u', 'o', 'x'],
['e', 'r', 'm', 'e'],
['y', 'y', 'e', 'x']
]
是否可以取sorted_key的顺序排序到unsorted_key中,取密文的顺序,以相同的方式排序?
将 'q' 从 sorted_key[4] 移动到 sorted_key[0] 时,应该将 ciphertext[4] 移动到 ciphertext[0]。
我一直在考虑它,我能想到的唯一方法是使用辅助函数从 unsorted_key 的顺序动态生成和返回一个 lambda 函数,然后使用类似的东西:
sorted_key, ciphertext = (list(i) for i in zip(*sorted(zip(sorted_key, ciphertext), key=generate(unsorted_key))))
但我真的不知道 zip() 或 lambda 函数是如何工作的,也不知道如何将自定义排序顺序合二为一,或者甚至可以返回以在 sorted() 中使用。我似乎真的无法解决这个问题,所以任何帮助将不胜感激!
在线性时间内解决这个问题的一种有效方法是创建一个将键映射到索引的sorted_key
字典,然后创建一个映射字典,将索引映射unsorted_key
到sorted_key
基于相同键的索引,以便您可以通过ciphertext
按映射顺序生成列表的长度范围:
order = dict(map(reversed, enumerate(sorted_key)))
mapping = {i: order[k] for i, k in enumerate(unsorted_key)}
print([ciphertext[mapping[i]] for i in range(len(ciphertext))])
这输出:
[['x', 'h', 'm', 's'], ['e', 'r', 'm', 'e'], ['u', 't', 'x', 'e'], ['l', 'x', 'c', 'x'], ['x', 'c', 'y', 'a'], ['y', 'y', 'e', 'x'], ['t', 'u', 'o', 'x'], ['p', 'r', 'k', 'p'], ['v', 'n', 'x', 'a'], ['n', 'h', 'e', 'x']]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句