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']
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']
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']
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 ;)