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

Time:09-28

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?

CodePudding user response:

just use list.sort()

#define list
a = ["tank", "ream", "ram", "banter"]

#sort list
a.sort()

CodePudding user response:

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']
  • Related