I've this lise:

lst = ['10:User1', '80:User2', '100:User3', '00:User4', '75:User4', '45:User5']

I want to print it as:

100 User3
80 User2
75 User4
45 User5
10 User1
00 User4

So, I want to organize them by the number.

5 Years
Discussion Span
Last Post by pyTony
>>> lst = ['10:User1', '80:User2', '100:User3', '00:User4', '75:User4', '45:User5']
>>> print(sorted(lst, key=lambda x: int(x.split(':',1)[0])))
['00:User4', '10:User1', '45:User5', '75:User4', '80:User2', '100:User3']
>>> print(sorted(lst, key=lambda x: int(x.split(':',1)[0]), reverse=True))
['100:User3', '80:User2', '75:User4', '45:User5', '10:User1', '00:User4']

key parameter defines sorting order, in this case we take first part before ':' and make it integer for comparison in nameless lambda function. If you feel unconfortable with lambda you can also define the function separately with name with def and give it as key parameter.

Edited by pyTony: n/a


Thank you :)

Please, mark your threads solved after you have got your answer. Helpfull posts anywhere can also be upvoted and optionally given good reputation.


I have a thousands of IP addresses, repeating randomly in my database and I wish to print each IP address along with the number of times they are repeated.

For example,

Output: - 3 - 3 - 1

I have used Counter() to do this manually by listing them individually and then using Counter(list). As there are thousands of IP addresses, it is impossible to list them out manually in the program. Is there any way where I can get the output with a for loop or anything else?

Editor's note:
Please do not hijack an existing thread, start your own thread with the appropriate title.

Edited by vegaseat: hijack


What you mean? What is problem with Counter?

from collections import Counter
print(Counter(ip.rstrip() for ip in open('ips.txt')))
""" Output:
Counter({'': 3, '': 3, '': 1})
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.