Search code examples
pythonpython-3.xfunctional-programming

how to sort a list by the strings that have the most alphabetical characters python


If there is a list with some strings, how the list be sorted where the strings within it are sorted by the most alphabetical of their character sequences if their character sequences were to be rearranged in alphabet order? For instance: ["tank", "ream", "ram", "banter"] would result in ["banter", "ream", "ram", "tank"]. Is this possible to achieve without loops and comprehension? i.e using lambdas?

As someone mentioned below sorted(words, key=sorted)) does work here but now I'm wondering about case sensitivity. How could this be handled if case sensitivity took precedence, meaning alphabet order of the character sequence but putting uppercase first?


Solution

  • Technically speaking, shouldn't the output be:

    ['banter', 'ream', 'tank', 'ram']
    

    Because for this input

    words = ["tank", "ream", "ram", "banter"]
    

    If we alphabetically rearrange each word

    >>> [''.join(sorted(word)) for word in words]
    ['aknt', 'aemr', 'amr', 'abenrt']
    

    And sorting that would result in the first output when reordered to the original wording.

    If so, then this should work:

    >>> sorted(words, key=sorted))
    ['banter', 'ream', 'tank', 'ram']