计算wxListBox中最常用的字符串

2024-10-01 13:44:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个wxListBox,其中填充了用户输入的字符串(客户名称)。我必须计算列表中出现次数最多的名字和出现次数最少的名字。我必须使用循环

下面是实际代码与伪代码的混合,但我在逻辑上遇到了问题:

cust_name = ""
for names in range(self.txtListBox.GetCount()):
    for compareName in counterList:
        if:
            names == compareName: 
            count += 1
        else:
            add names to counterList
            set count to 1 

用Python中的循环实现这一点的最佳方法是什么


Tags: to字符串代码用户in名称for客户
1条回答
网友
1楼 · 发布于 2024-10-01 13:44:51

使用collections.Counter来计算姓名

from collections import Counter

names = ["foo","foo","foobar","foo","foobar","bar"]

c =  Counter(names).most_common() # returns a list of tuples from most common to least

most_com, least_com = c[0][0],c[-1][0] # get first which is most common and last which is least
print most_com,least_com
foo bar

使用循环,只需调用Counter.update

c =  Counter()

for name in names:
    c.update(name)

c = c.most_common()
most_com, least_com = c[0][0],c[-1][0]

如果无法导入模块,请使用普通dict:

d = {}
for name in names:
    d.setdefault(name,0)
    d[name] += 1
print d
{'foobar': 2, 'foo': 3, 'bar': 1}
srt = sorted(d.items(),key=lambda x:x[1],reverse=True)
most_com,least_com = srt[0][0],srt[-1][0]

相关问题 更多 >