1

I have a List e.g.:

Name - Seconds: 3.14 - Mistakes: 0
DsO - Seconds: 7.09 - Mistakes: 0
Xardas - Seconds: 7.24 - Mistakes: 0
Badudu1 - Seconds: 13.55 - Mistakes: 1

How can I sort it by seconds?

So the user types in his name which is the first entry before the " - "

I tried it with this:

seconds_position = len(user_input) + len(" - Seconds: ")
seconds = substring[seconds_position]
seconds = seconds.partition(" ")[0]

I guess that I could just do this for every list entry and compare them but how do I compare it when the seconds are two-digit before the comma?

0

4 Answers 4

2

Use re module with .sort or sorted:

import re

new_list = sorted(original_list, key=lambda x: float(re.search('Seconds:\s(\d+\.\d+)', x).group(1)))

To do it inplace use:

original_list.sort(key=lambda x: float(re.search('Seconds:\s(\d+\.\d+)', x).group(1)))

Edit:

if you don't want to use a library change the key to:

key = lambda x: float(x.split('-')[1][10:-1])
Sign up to request clarification or add additional context in comments.

1 Comment

Unfortunately I'm not allowed to import something. Is there another way?
0

You can give a key to sorted function and that key can be a lambda function. change lst with the name of your list. This takes the float part of the list item.

sorted(lst, key=lambda x: float(x.split('-')[1][len(' Seconds: '):]))

Comments

0

if you use timedelta you can then make arithmetic operations on your seconds

a="""Name - Seconds: 3.14 - Mistakes: 0
DsO - Seconds: 7.09 - Mistakes: 0
Xardas - Seconds: 7.24 - Mistakes: 0
Badudu1 - Seconds: 13.55 - Mistakes: 1"""
from datetime import timedelta
deltas=[]
for line in a.splitlines():
    seconds=line.split(' - ')[1].split(':')[1].strip()
    deltas.append(timedelta(seconds=float(seconds)))
print(deltas[0]+2*deltas[1])
>>> 0:00:17.320000

Comments

0

Use the key parameter of the sort method to extract the numeric value of seconds in each string:

Depending on the patterns that are possible in your strings, this extraction could be as simple as a split or it may require more sophisticated parsing (using a regular expression for example).

Here is an example with a simple split:

L = ["Name - Seconds: 3.14 - Mistakes: 0",
     "Badudu1 - Seconds: 13.55 - Mistakes: 1",
     "DsO - Seconds: 7.09 - Mistakes: 0",
     "Xardas - Seconds: 7.24 - Mistakes: 0",
]

L.sort(key=lambda i:float(i.split()[3]))

print(L)
['Name - Seconds: 3.14 - Mistakes: 0', 
 'DsO - Seconds: 7.09 - Mistakes: 0', 
 'Xardas - Seconds: 7.24 - Mistakes: 0', 
 'Badudu1 - Seconds: 13.55 - Mistakes: 1']

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.