How to sort a list by length of string followed by alphabetical order?
You can do it in two steps like this:
the_list.sort() # sorts normally by alphabetical order
the_list.sort(key=len, reverse=True) # sorts by descending length
Python's sort is stable, which means that sorting the list by length leaves the elements in alphabetical order when the length is equal.
You can also do it like this:
the_list.sort(key=lambda item: (-len(item), item))
Generally you never need cmp
, it was even removed in Python3. key
is much easier to use.
Sort elements in list based on length first and alphabetical order second
use key
argument of sorted function. convert each element to a tuple of priority. here (len(s), s), this means len(s)
have more priority to s
.
proxy_list = ['my', 'list', 'looks', 'like', 'this']
print(sorted(proxy_list, key=lambda s: (len(s), s)))
#>>> ['my', 'like', 'list', 'this', 'looks']
Sort string array by line length AND alphabetically at once
If you sort twice, the second sorting will not take the rules of the first sorting into account.
You must sort once, and the sorting rule(s) must include all properties you want to sort by.
So primarily you want to sort by length. And if 2 elements have the same length, then by natural order. You can achieve this by first checking the lengths in the less()
function. If they are not equal, then the order by length is what decides the result. If they are equal, you resort to natural order.
list := strings.Split("2 22 2H 2J 2J2 2J3 2J322422 2J322423 2J33 2M 2P 2W 2X", " ")
fmt.Println(list)
sort.Slice(list, func(i, j int) bool {
l1, l2 := len(list[i]), len(list[j])
if l1 != l2 {
return l1 < l2
}
return list[i] < list[j]
})
fmt.Println(list)
This will output (try it on the Go Playground):
[2 22 2H 2J 2J2 2J3 2J322422 2J322423 2J33 2M 2P 2W 2X]
[2 22 2H 2J 2M 2P 2W 2X 2J2 2J3 2J33 2J322422 2J322423]
You can extend this logic to sort by any number of properties (or rules). You check the higher priority rules first, and if they define difference in order, you return the order designated by them (the information whether the i
th element is less than the j
th). If they don't differentiate the positions of the elements in question, you proceed with lower priority rules.
Sort string array first on length then alphabetically in Python 3
Firstly, using just sorted
will not sort alphabetically, look at your output... I am pretty sure L
does not come before a
. What you are currently doing is a case-sensitive sort.
You can perform a case-insensitive sort by using a Key Function like so:
>>> words_list = ["Lorem", "ipsum", "dolor", "sit", "amet", "consectetur", "adipiscing", "elit", "sed", "do", "eiusmod", "tempor", "incididunt"]
>>> sorted(words_list, key=str.lower)
['adipiscing', 'amet', 'consectetur', 'do', 'dolor', 'eiusmod', 'elit', 'incididunt', 'ipsum', 'Lorem', 'sed', 'sit', 'tempor']
You can then modify the Key Function like below to sort first on length then alphabetically:
>>> def custom_key(str):
... return -len(str), str.lower()
...
>>> sorted(words_list, key=custom_key)
['consectetur', 'adipiscing', 'incididunt', 'eiusmod', 'tempor', 'dolor', 'ipsum', 'Lorem', 'amet', 'elit', 'sed', 'sit', 'do']
How to sort a list by length and then in reverse alphabetical order
Just use the reversed
function:
a = list(reversed(sorted(a, key=lambda x: (-len(x), x))))
In [301]: a
Out[301]: ['b', 'a', 'zzz', 'ddd', 'ccc']
Java sort list with streams first by length then alphabetically
If you need to sort first by description length and then by description (alphabetical order), then your first comparison is fine but you also need to add a second comparison by description.
You can stack a second comparison by using the method thenComparing()
. It will perform the second comparison only for elements with same length. There is no need to implement a custom Comparator
for this scenario.
public List<Article> sortAsc() {
removeNull();
return articles.stream()
.sorted(Comparator.comparingInt((Article a) -> a.getDescription().length())
.thenComparing(Article::getDescription))
.collect(Collectors.toList());
}
Related Topics
How to Use Type Hints in Python 3.6
Importerror: No Module Named Win32Com.Client
How to Parse Somewhat Wrong JSON with Python
Django Equivalent for Count and Group By
How to Execute a Command Prompt Command from Python
How to Sort and Remove Duplicates from Python List
Reading/Writing Ms Word Files in Python
Skip Multiple Iterations in Loop
Using Lxml and Iterparse() to Parse a Big (+- 1Gb) Xml File
Error "Importerror: Dll Load Failed: %1 Is Not a Valid Win32 Application"
Schedule a Repeating Event in Python 3
How to Invoke Pandas.Rolling.Apply with Parameters from Multiple Column