Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,690 questions

55,449 answers

573 users

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

...