Sorting Python list based on the length of the string
When you pass a lambda
to sort
, you need to return an integer, not a boolean. So your code should instead read as follows:
xs.sort(lambda x,y: cmp(len(x), len(y)))
Note that cmp is a builtin function such that cmp(x, y)
returns -1 if x
is less than y
, 0 if x
is equal to y
, and 1 if x
is greater than y
.
Of course, you can instead use the key
parameter:
xs.sort(key=lambda s: len(s))
This tells the sort
method to order based on whatever the key function returns.
EDIT: Thanks to balpha and Ruslan below for pointing out that you can just pass len
directly as the key parameter to the function, thus eliminating the need for a lambda
:
xs.sort(key=len)
And as Ruslan points out below, you can also use the built-in sorted function rather than the list.sort
method, which creates a new list rather than sorting the existing one in-place:
print(sorted(xs, key=len))
Sort list of strings in decreasing order (according to length)
You can simply use (-len(x), x)
instead of (len(x), x)
and reverse=True
.
>>> sample_list = ['a', 'bb', 'cc', 'ddd', 'bbc']
>>> sorted(sample_list, key=lambda x: (-len(x), x))
['bbc', 'ddd', 'bb', 'cc', 'a']
This will sort the list with decreasing order of length first (because of -len(x)
), and then sort the strings with the same length in a lexicographical order.
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']
How to sort a list of lists based on length of inner list?
Using sort
or sorted
with custom key.
Ex:
data = [['A', '1234', 'X'],['B', '12', 'X'],['C', '12345', 'X'],['D', '123', 'X']]
data.sort(key=lambda x: len(x[1]), reverse=True)
or sorted
data = sorted(data, key=lambda x: len(x[1]), reverse=True)
print(data)
Sorting list of strings by their length and the last N characters
Use x[::-1]
.
Ex:
l = [['apple', 'banana', 'grape', 'kiwi', 'pear'], ['airplane', 'bicycle', 'boat', 'car']]
for i in l:
print(sorted(i, key=lambda x: (x[::-1], len(x))))
Output:
['banana', 'apple', 'grape', 'kiwi', 'pear']
['bicycle', 'airplane', 'car', 'boat']
output = [sorted(i, key=lambda x: (x[::-1], len(x))) for i in l]
print(output)
--> [['banana', 'apple', 'grape', 'kiwi', 'pear'], ['bicycle', 'airplane', 'car', 'boat']]
Sort list in pandas series by length of string
You can use pd.Series.apply
with sorted
:
def sorter(x):
return sorted(x, key=len, reverse=True)
df['serie'] = df['serie'].apply(sorter)
How to sort array based on length and alphabet, where alphabet takes precedence over length python
You can use a sort key with a tuple:
d = ["@note1", "@note2", "=dir1/", "=dir2/", "@dir1/note1", "@dir1/note2"]
new_d = sorted(d, key=lambda x:(x[1:], len(x)))
Output:
['=dir1/', '@dir1/note1', '@dir1/note2', '=dir2/', '@note1', '@note2']
Related Topics
Remove Namespace and Prefix from Xml in Python Using Lxml
Can Existing Virtualenv Be Upgraded Gracefully
How to Separate the Functions of a Class into Multiple Files
Stop/Start/Pause in Python Matplotlib Animation
What's a Faster Operation, Re.Match/Search or Str.Find
Matplotlib Savefig() Plots Different from Show()
How to Qcut with Non Unique Bin Edges
How to Convert an Array of Strings to an Array of Floats in Numpy
How to Loop Through All But the Last Item of a List
Python Pandas: How to Specify Data Types When Reading an Excel File
How to Get a Raw, Compiled SQL Query from a SQLalchemy Expression
In Python What Is a Global Statement
How to Use Groupby to Concatenate Strings in Python Pandas