If i wanted a list that contains numbers and words, like this one
random_list=["h: 100", "g: 57", "k: 1", "p: 200"]
Sorted numerically so it becomes
["k: 1", "g: 57", "h: 100", "p: 200"]
What would be the code in python 3?
If i wanted a list that contains numbers and words, like this one
random_list=["h: 100", "g: 57", "k: 1", "p: 200"]
Sorted numerically so it becomes
["k: 1", "g: 57", "h: 100", "p: 200"]
What would be the code in python 3?
Python sorting allows for a key
keyword that can be used to define your own sorting method. The below code is for Python 2.7, I assume 3 is similar:
random_list=["h: 100", "g: 57", "k: 1", "p: 200"]
sorted(random_list, key=lambda x: int(x.split()[1]))
# ['k: 1', 'g: 57', 'h: 100', 'p: 200']
Firstly, that's a wrong data structure. You either mean a list or a dictionary.
Since the contents of your 'list' are key-value pairs, I'm guessing what you need is a dictionary instead. Dictionaries have the sorted() function available to them.