NsanitY
NsanitY

Reputation: 13

How to split the most common value and its occurrence count

so i am attempting to display the most common element in a txt file which has 10,000 lines in it. and then display how many times the most common element occurrs.

So far i have the code down and it displays the most common value and the occurrences, however, i would like to display it as:

Most common is: "most common element", It appears "xxxx" times.

I am using the Counter function to count the occurrences i just need to be able to separate the key from the value is this possible?


readfile = open(filename, 'r')

def most_frequent(my_list2):
    counter = 0
    num = my_list2 [0]

    for i in my_list2:
        curr_frequency = my_list2.count(i)
        if(curr_frequency> counter):
            counter = curr_frequency
            num = i
    return num

my_list2 = []
from collections import Counter
for word in readfile:
    my_list2.extend(word.split(None)[:1])
    c=Counter(my_list2)
    c.most_common (1)
 
print("The most common IP Address is:", ( c.most_common(1)))

the ouput is: Enter the name of the file: ip_list.txt The most common IP Address is: [('172.16.10.207', 535)]

How do i separate the ,535 to a seperate string?

Thanks for your help

Upvotes: 0

Views: 88

Answers (1)

2pichar
2pichar

Reputation: 1378

You can unpack the array and tuple:

ip, count = c.most_common(1)[0]
print(f"Most common: {ip}, count: {count}")

Upvotes: 1

Related Questions