如何在不使用计数或计数器的情况下计算列表项的出现次数?

时间:2018-11-09 04:06:57

标签: python count

我有一个单词列表,想知道有多少个独特的单词。我最终将列表导入字典,显示每个单词有多少个。

现在我有

while i < len(list_words): 
    if list_words[i] in list_words:
        repetitions += 1 
    i += 1
print(repetitions)

但这只是返回列表的长度。

7 个答案:

答案 0 :(得分:3)

defaultdictspec.source_files = 'VideoRow/**/*.[mh]'一起使用:

int

如果您想知道唯一的单词,请使用

from collections import defaultdict

l = ['apple','banana','pizza','apple','banana']

d = defaultdict(int)
for k in l:
    d[k] += 1

print(d)
defaultdict(<class 'int'>, {'apple': 2, 'banana': 2, 'pizza': 1})

要获取唯一单词的数量,请使用:

keys = list(d.keys())
[keys[index] for index, value in enumerate(d.values()) if value == 1]
['pizza']

答案 1 :(得分:3)

尝试一下

    word_counts = dict.fromkeys(list_words, 0)

    for word in list_words:
        word_counts[word] += 1

答案 2 :(得分:0)

您可以通过公式length of words list - length of unique words list轻松获得它,该公式可以由len(list_words) - len(set(list_words))计算。无需循环。

答案 3 :(得分:0)

lenlist comprehension

>>> l = ['apple','banana','pizza','apple','banana']
>>> len([i for i in l if i == 'apple']) # for example we want "apple" to be the one to count.
2
>>>  

答案 4 :(得分:0)

一种可能是这样:

list_words = ["cat", "mouse", "cat", "rat"]
i = 0
dictionary = {}
result = 0

for unique_word in set(list_words):

    word_occurances = 0

    for word in list_words:
        if word == unique_word:
            word_occurances += 1

    dictionary[unique_word] = word_occurances

for word in dictionary:
    if dictionary[word] == 1:
        result += 1  

print("There are " + str(result) + " unique words")

答案 5 :(得分:0)

这是针对python 2.7



    list_words = ["a","b","c","a","b","b","a"]
    d = {}
    for word in list_words:
        if word in d.keys():
            d[word]+=1
        else:
            d[word]=1

    print "There are %d different words and they are: %s"%(len(d.keys()), d.keys())
    print d

答案 6 :(得分:-1)

已更新

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    if (keyData == (Keys.Control | Keys.A))
    {
        MessageBox.Show("You pressed Ctrl+A!");

        return true;
    }

    return false;
}

退出:

ls = ["apple", "bear", "cat", "cat", "drive"]
lu = set(ls)

d = {}
for s in ls:
    if s in d.keys():
        d[s] += 1
    else:
        d[s] = 1

print(d["cat"]) # counts a word in the list
print([s for s in lu if d[s] > 1]) # Multiply values
print(lu) # Unique values
print(d) # Number of unique words