【发布时间】:2019-02-21 19:46:16
【问题描述】:
例如有三个列表:
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]。
- 所有三个列表的长度始终相同。
- sorted_key 和 unsorted_key 永远不会有重复的元素。
- sorted_key 将始终是 unsorted_key 的排序版本。
我一直在考虑,我能想到的唯一方法是使用辅助函数从unsorted_key的顺序动态生成并返回一个lambda函数,然后使用类似的东西:
sorted_key, ciphertext = (list(i) for i in zip(*sorted(zip(sorted_key, ciphertext), key=generate(unsorted_key))))
但我真的不知道 zip() 或 lambda 函数是如何工作的,也不知道如何将自定义排序顺序合二为一,或者是否甚至可以返回一个以在 sorted() 中使用。我真的无法解决这个问题,所以任何帮助将不胜感激!
【问题讨论】:
-
x似乎没有出现在unsorted_key中,但确实存在于ciphertext的最后一行。缺失的元素应该如何排序? -
它应该将
ciphertext[4]移动到ciphertext[0]- 这些是列表 - 不是字符... -
@PatrickArtner
'x'是密文元素(列表)中的一个字符。密文只是一个列表,在这个例子中它恰好是一个列表列表,但它可以是任何东西的列表,重要的是密文中元素的顺序,而不是元素本身的内部顺序。
标签: python python-3.x sorting