1

Here's my .txt file

-22, www 1213
-25, ttt 1234
-20, yyy 8883

I want to order the lines based on the first number.

I tried like this:

f = open('file_.txt','rb')
text = f.readlines()
sorted(text, key=lambda row: row[0], reverse=True)

but the order is the same. Using a variation for the sorted line

sorted(text, key=lambda row: float(row[0]), reverse=True)

I get the following error:

ValueError: could not convert string to float: -

What am I doing wrong?

0

2 Answers 2

2
sorted(text, key=lambda row: float(row.split()[0].rstrip(',')), reverse=True)

The problem was that you were sorting by the first character, you want the first word (without the comma), you could also split by the comma.

Sign up to request clarification or add additional context in comments.

Comments

1

The reason that your sorting lambda isn't working is because row[0] is the first character, not the first value. You could change it to row.split(',')[0], and it will work as intended. Also, it's best practice to use the with statement for opening files.

with open('file_.txt','rb'):
    text = f.readlines()
sorted(text, key=lambda row: row.split(',')[0], reverse=True)

In your second example, you're getting the value error for the same reason, you're essentially saying float("-22, www 1213"). if you really wanted to do that it would be

    float(row.split(',')[0])

and if there might be whitespace:

    float(row.split(',')[0].strip())

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.