计算列表中元素的频率,并按字母顺序打印这些元素

2024-04-19 21:12:44 发布

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

我有问题。我必须计算列表中元素的频率,并且必须按字母顺序打印这些元素。任务是:https://1drv.ms/i/s!AqbJai99OU_ejy-jF_wOYaQCFjHR

我这样说:

**>>>from collections import Counter
>>>text= "he he he he she it she it she it and and and "
>>>words=text.split()
>>>counter=Counter(words)
>>>top_three=counter.most_common(4)
>>>top_three.sort(key=lambda x: (-x[1], x[0]))
>>>print(top_three)**

但是当我进行测试运行时,我遇到了一个问题:https://1drv.ms/i/s!AqbJai99OU_ejzBadWfydEv6oGpa

我知道我必须使用count\u words函数,但我不知道怎么做。 如果你知道,请写信给我:D


Tags: andtexthttps元素列表topcounterit
1条回答
网友
1楼 · 发布于 2024-04-19 21:12:44

这是一种更简单的方法来获得相似单词的计数并对它们进行排序。你知道吗

text = 'he he he he she it she it she it and and and'

wordlist = text.split()
wordlist.sort()

wordfreq = []
for w in wordlist:
    wordfreq.append(wordlist.count(w))
    print(w)

print()
print("String\n" + text +"\n")
print("List\n" + str(wordlist) + "\n")
print("Frequencies\n" + str(wordfreq) + "\n")

@D.Tarik下面的代码可以按照你的要求工作。如果你认为答案正确并且对你有帮助,请接受。你知道吗

def count_word(text):

    wordlist = text.split()
    wordlist.sort()
    my_list = []

    for i in wordlist:
        if i not in my_list:
            word_count = wordlist.count(i)
            my_list.append((i,word_count))
    print(set(my_list))


count_word('he he he he she it she it she it and and and')

输出:

{('he', 4), ('and', 3), ('it', 3), ('she', 3)}

相关问题 更多 >