0

I am trying to sort a list of strings. Each string contains numbers and letters and they are separated by space. I want to sort the list based on the numbers.

Example code:

list=["x 10","y 20"]

2 Answers 2

2

You may sort with the help of a lambda:

list = ["x 10", "y 20", "z 15"]
list_sorted = sorted(list, key=lambda x: int(x.split()[1]))
print(list_sorted)  # ['x 10', 'z 15', 'y 20']

In the snippet above, the lambda expression splits each list element by space, and then casts the second element to an integer. It is this value which is then used to sort the list.

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

Comments

0
l=["x 10","y 20","z 15"]

n=len(l)

for i in range(n-1):

    for j in range(n-i-1):

        if int(l[j].split()[1])>int(l[j+1].split()[1]):
            l[j],l[j+1]=l[j+1],l[j]

print(f"sorted{l}")

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.