根据另一个列表中的模式对嵌套列表进行排序

Sort nested list based on pattern in another list

我有以下问题:

待排序列表:

[['[check116] Ensure ...', 'azure-ad-role-manager ...'],
['[check28] Ensure ...', 'eu-west-1: Key ...', 'eu-central-1: Key ...'], 
['[check41] Ensure ...', 'Found ...']]

模式:

["[check28] Ensure ...",
"[check116] Ensure ...",
"[check41] Ensure ..."]

期望的输出:

[['[check28] Ensure ...', 'eu-west-1: Key ...', 'eu-central-1: Key ...'], 
['[check116] Ensure ...', 'azure-ad-role-manager ...'],
['[check41] Ensure ...', 'Found ...']]

我试过: Sorting list based on values from another list 和其他一些解决方案 - 但它们主要基于对模式的 int 值进行排序,而我的问题并非如此。

提前感谢您提供任何提示或解决方案。

您可以在 key= 函数中使用 list.index

lst = [
    ["[check116] Ensure ...", "azure-ad-role-manager ..."],
    ["[check28] Ensure ...", "eu-west-1: Key ...", "eu-central-1: Key ..."],
    ["[check41] Ensure ...", "Found ..."],
]

pattern = [
    "[check28] Ensure ...",
    "[check116] Ensure ...",
    "[check41] Ensure ...",
]

out = sorted(lst, key=lambda k: pattern.index(k[0]))
print(out)

打印:

[
    ["[check28] Ensure ...", "eu-west-1: Key ...", "eu-central-1: Key ..."],
    ["[check116] Ensure ...", "azure-ad-role-manager ..."],
    ["[check41] Ensure ...", "Found ..."],
]