How to sort by numbers a mixed pair of string and number elements in a list with Python

3 Answers

0 votes
def get_number_from_mixed_pair_list(mixed_pair_lst):
   s, n = mixed_pair_lst.split()
    
   return int(n)  


mixed_pair_list = ['Python 4', 'C 9', 'C++ 5', 'C# 6', 'Java 1', 'PHP 7', 'Go 2']

sorted_mixed_pair_list = sorted(mixed_pair_list, key=get_number_from_mixed_pair_list)
 
print(sorted_mixed_pair_list)
 
 
   
'''
run:
   
['Java 1', 'Go 2', 'Python 4', 'C++ 5', 'C# 6', 'PHP 7', 'C 9']
   
'''

 



answered Jan 22 by avibootz
edited Jan 22 by avibootz
0 votes
def get_number_from_mixed_pair_list(mixed_pair_lst):
   return sorted(mixed_pair_list, key=lambda x: int(x.split()[-1]))


mixed_pair_list = ['Python 4', 'C 9', 'C++ 5', 'C# 6', 'Java 1', 'PHP 7', 'Go 2']

sorted_mixed_pair_list = get_number_from_mixed_pair_list(mixed_pair_list)
 
print(sorted_mixed_pair_list)
 
 
   
'''
run:
   
['Java 1', 'Go 2', 'Python 4', 'C++ 5', 'C# 6', 'PHP 7', 'C 9']
   
'''

 



answered Jan 22 by avibootz
edited Jan 22 by avibootz
0 votes
def extract_number(s):
    pos = s.rfind(" ")
    
    return int(s[pos + 1:])

lst = [
    "Python 4", "C 9", "C++ 5", "C# 6",
    "Java 1", "PHP 7", "Go 2"
]

sorted_lst = sorted(lst, key=extract_number)

for item in sorted_lst:
    print(item)



   
'''
run:
   
Java 1
Go 2
Python 4
C++ 5
C# 6
PHP 7
C 9
   
'''

 



answered Jan 22 by avibootz

Related questions

...