我有以下问题:
待排序列表:
[['[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 ...']]
我尝试过:根据其他列表中的值对列表进行排序以及其他一些解决方案,但它们主要基于对模式的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 ..."],
]