'How Can i Arrange a list of integers in python in txt file? [duplicate]
How can I arrange a list of integers in python in txt file? Example = I am having:
['45 USD\n', '68 USD\n', '32 USD\n', '894 USD\n']
I want to arrange them in this order:
['894 USD\n', '68 USD\n', '45 USD\n', '32 USD\n']
Solution 1:[1]
If all the strings in the list will have the same format, you could create a lambda function to sort them removing the "string" part and casting them to integers, as in:
L = ['45 USD\n', '68 USD\n', '32 USD\n', '894 USD\n']
print(sorted(L, key=lambda x: int(x[:-6]), reverse=True)) # x[:-6] removes the last 6 characters " USD\n"
result being:
['894 USD\n', '68 USD\n', '45 USD\n', '32 USD\n']
Solution 2:[2]
You can use the sort function for this.
a=['45 USD\n', '68 USD\n', '32 USD\n', '894 USD\n']
a.sort(reverse=True, key=lambda x: int(x.split()[0]))
print(a) # ['894 USD\n', '68 USD\n', '45 USD\n', '32 USD\n']
See this
Hope it helps ;)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Shunya |
| Solution 2 | Circuit Planet |
