简体   繁体   中英

Sort nested list based on pattern in another list

I have following problem:

List to be sorted:

[['[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 ..."]

Desired output:

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

I've tried: Sorting list based on values from another list and few other solutions - but they mainly base on sorting the pattern's int values, and it's not the case in my problem.

Thanks in advance for any hints or solutions.

You can use list.index in your key= function:

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)

Prints:

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

Probably you can try this,

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

sorted(input_, key=lambda x: len(x), reverse=True)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM