Reputation: 97
i have an issue with a .txt list, the list contains the next:
Numero de permutaciones de la forma (2,4,3) = 1260
Numero de permutaciones de la forma (7,2,0) = 36
Numero de permutaciones de la forma (5,3,1) = 504
Numero de permutaciones de la forma (4,5,0) = 126
Numero de permutaciones de la forma (1,8,0) = 9
Numero de permutaciones de la forma (0,7,2) = 36
Numero de permutaciones de la forma (0,6,3) = 84
...
my code is this:
with open('resultado_lista_original2.txt', 'r') as r:
for line in sorted(r):
print(line,end='')
but i need to sort that list by the element next to right the "=" to get this order
Numero de permutaciones de la forma (1,8,0) = 9
Numero de permutaciones de la forma (0,7,2) = 36
Numero de permutaciones de la forma (7,2,0) = 36
Numero de permutaciones de la forma (0,6,3) = 84
Numero de permutaciones de la forma (4,5,0) = 126
Numero de permutaciones de la forma (5,3,1) = 504
Numero de permutaciones de la forma (2,4,3) = 1260
...
I appreciate very much who can help me / guide me
Upvotes: 0
Views: 67
Reputation: 98861
Late answer, but you can also use:
import re
with open("input.txt")as f:
s = sorted(f, key=lambda x:int(re.search(r"(\d+)$", x).group(1)))
Upvotes: 1
Reputation: 7509
Pass in the key
argument to decide how to sort your iterable. Most people do this using a lambda function:
for line in sorted(r, key=lambda x: int(x.split('=')[1])):
Or if you prefer to define the function yourself:
def sort_my_txt_lines(line):
digits_after_equal_sign = line.split('=')[1]
return int(digits_after_equal_sign)
# ...
for line in sorted(r, key=sort_my_txt_lines):
If you're not used to think about sorting using a key
function, think about it like this: when trying to sort the input sequence, only look at the numerical part beyond the =
sign (the function's return value) of each line (the function's input parameter).
Upvotes: 3
Reputation: 61
The sorted
method has an attribute key where you can put a lambda or a method which will be called with each item of the list that you want to sort.
The result of that will be used for to sort the list instead of the item itself.
Upvotes: 1
Reputation: 942
Try this:
for line in sorted(r, key=lambda x: int(x.split(' = ').strip())):
Upvotes: 0