-1

I havent tried anything for im clueless when it'd come to this but I wish to sort a list that looks like this. the thing is a string its laid out like this though:

Name:intvalue:othervalue

I want it to sort the list by the size of what intvalue is nothing else so say theres a list like below

I havent tried any code but heres an example of what I except to happen:

['gop:1245:random', 'random:35:eee', 'random3:100000:efa']

The sorted list should end up being

['random:35:eee', 'gop:1245:random', 'random3:100000:efa']
Psytho
  • 3,313
  • 2
  • 19
  • 27
  • This question might help: [How to correctly sort a string with a number inside?](https://stackoverflow.com/questions/5967500) – Jorge Luis Apr 19 '23 at 11:55
  • Ye I saw that and my eyes lit up but realised that it'd look at all like yk for all numbers in the string not just the middle of the string – Notepad noobb Apr 19 '23 at 11:56
  • Hi your other respond is that a loop or is it looking at all values at once? – Notepad noobb Apr 19 '23 at 11:57
  • @Notepasnoobb The [Python documentation](https://docs.python.org/3/howto/sorting.html#key-functions) asserts the lambda function will be called exactly one for every element in your list. – Jorge Luis Apr 19 '23 at 13:44

2 Answers2

0

list.sort method and sorted builtin both have key argument where you can pass the function that takes the single element and gets what you want to use for comparison.

So let's write the key function:

def get_int_from_elem(elem):
    parts = elem.split(":")
    num = int(parts[1])
    return num

It can be also an inline lambda: lambda e: int(e.split(":")[1]) but I wanted to show the full form for readability.

So let's say your list is named my_list

If you want to change the current list, use the method. Remember the methods that change stuff in-place return None, so you don't save result of those:

my_list.sort(key=get_int_from_elem)
print(my_list)

Or if you want a copy (my_list) doesn't get changed, use sorted and save the result:

new_list = sorted(my_list, key=get_int_from_elem)
print(new_list)
h4z3
  • 5,265
  • 1
  • 15
  • 29
-1
lst = ['random:35:eee', 'gop:1245:random', 'random3:100000:efa']
lst.sort(key=lambda x: int(x.split(":")[1]))

I recommend using lambda function

DevRuby
  • 1
  • 2