I have a list of strings and integers and want to sort the list, preserving the numbers like so
["Hello", 1, 2, "World", 6, "Foo", 3]
would become
["Foo", 1, 2, "Hello", 6, "World", 3]
In short, it only sorts the strings in the list, not the integers, which stay in place. I've tried using the key
parameter with list.sort()
but haven't managed to achieve what I want.
Can anyone help me with this?
EDIT: this is different to the linked question as I want to preserve the integers' indexes, rather than sort them along with the strings.
EDIT: this is different to the second linked question as answers from that question can solve the problem using the key
parameter, something I have explicitly stated does not work in this instance.
In this, we use sorted() functionality to perform sort operation and join() is used to reconstruct the string list. The combination of above method can also be used to perform this task. In this, we perform the functionality of traversal using map() and lambda rather than list comprehension.
Use the Python List sort() method to sort a list in place. The sort() method sorts the string elements in alphabetical order and sorts the numeric elements from smallest to largest.
Python sorted() Function The sorted() function returns a sorted list of the specified iterable object. You can specify ascending or descending order. Strings are sorted alphabetically, and numbers are sorted numerically. Note: You cannot sort a list that contains BOTH string values AND numeric values.
To get a copy of the sorted list without modifying the original list, you can use the sorted() function, which returns a new sorted list. To sort the list in reverse order, you can use the reverse parameter for the sort(reverse=True) method.
Picked up this cool trick from @JonClements the other day.
Here goes:
gen = iter(sorted([x for x in lst if isinstance(x, str)]))
new_lst = [next(gen) if isinstance(x, str) else x for x in lst]
print(new_lst)
# ['Foo', 1, 2, 'Hello', 6, 'World', 3]
Sort the strings separately and create a generator expression from the sorted strings. In a list comprehension, pick objects alternately from the gen. exp. using a ternary conditional if only the items in the original position is a string, otherwise, pick an item (an integer) from the initial list.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With