Hello,
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.
Hello,
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.
>>> 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.
Thank you :)
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.
Hi,
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,
162.10.2.1
162.10.2.1
162.10.2.1
192.34.1.10
172.11.2.9
192.34.1.10
192.34.1.10
Output:
162.10.2.1 - 3
192.34.1.10 - 3
172.11.2.9 - 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.
What you mean? What is problem with Counter?
from collections import Counter
print(Counter(ip.rstrip() for ip in open('ips.txt')))
""" Output:
Counter({'192.34.1.10': 3, '162.10.2.1': 3, '172.11.2.9': 1})
"""
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.