Skip to main content
 首页 » 编程设计

python之使用 Python 计算列表中的字符串数

2025年05月04日25虾米姐

我手头有一个列表,我想从这个列表中创建词汇表。然后,我想显示每个单词并计算此列表中的相同字符串。

示例列表如下。

    new_list = ['one', 'thus', 'once', 'one', 'count', 'once', 'this', 'thus'] 

首先,我创建了一个词汇表。

    vocabulary = [] 
        for i in range (0, len(new_list)): 
            if new_list[i] not in vocabulary: 
                vocabulary.append(new_list[i])` 
    print vocabulary 

以上代码的输出是:“count, once, one, this, thus.”

我想显示列表中每个单词的数量,如下所示。 [count][1], [once][2], [one][2], [this][1], [thus][2].

为了得到上面的结果;我尝试下面的代码。

    matris = [] 
 
    for i in range(0,len(new_list)): 
        temp = [] 
        temp.insert(0,new_list.count(new_list[i]))         
        matris.append(temp) 
 
    for x in matris: 
        print x 

上面的代码只给出了字数。有人可以告诉我如何一起打印单词名称和单词数量,例如 [once][2] 格式。

请您参考如下方法:

使用 Counter dict 获取字数,然后遍历 .items:

from collections import Counter 
 
new_list = ['one', 'thus', 'once', 'one', 'count', 'once', 'this', 'thus'] 
 
cn = Counter(new_list) 
for k,v in cn.items(): 
    print("{} appears  {} time(s)".format(k,v)) 

如果您想要特定的输出,您可以将元素包装在 str.format 中:

for k,v in cn.items(): 
    print("[{}][{}]".format(k,v)) 
 
[thus][2] 
[count][1] 
[one][2] 
[once][2] 
[this][1] 

要获得从最高计数到最低计数的输出,请使用 .most_common:

cn = Counter(new_list) 
for k,v in cn.most_common(): 
    print("[{}][{}]".format(k,v)) 

输出:

[once][2] 
[thus][2] 
[one][2] 
[count][1] 
[this][1] 

如果您希望数据按字母顺序从最低到最高和从最高到最低的计数,您需要传递一个键 -x[1] 来排序以否定计数从最高排序计数到最低:

for k, v in sorted(cn.items(), key=lambda x: (-x[1],x[0])): 
    print("[{}][{}]".format(k, v)) 

输出:

[once][2] 
[one][2] 
[thus][2] 
[count][1] 
[this][1]