【问题标题】:How to split the most common value and its occurrence count如何拆分最常见的值及其出现次数
【发布时间】:2022-01-24 18:31:03
【问题描述】:

所以我试图在一个包含 10,000 行的 txt 文件中显示最常见的元素。然后显示最常见的元素出现的次数。

到目前为止,我已经完成了代码,它显示了最常见的值和出现次数,但是,我想将其显示为:

最常见的是:“最常见的元素”,出现“xxxx”次。

我正在使用 Counter 函数来计算出现次数,我只需要能够将键与值分开,这可能吗?


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)))

输出为:输入文件名:ip_list.txt 最常见的IP地址是:[('172.16.10.207', 535)]

如何将 ,535 分隔为单独的字符串?

感谢您的帮助

【问题讨论】:

  • 你得到的是元组列表。

标签: python python-3.x


【解决方案1】:

你可以解包数组和元组:

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

【讨论】:

  • 非常感谢 :)
  • most_common(1) 只会返回一个值,所以没有什么可忽略的
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-28
  • 2012-12-03
  • 1970-01-01
  • 1970-01-01
  • 2023-01-04
相关资源
最近更新 更多