Python 单词列表中最常见的10个字长

Python 单词列表中最常见的10个字长,python,Python,我正在编写一个函数,返回一个名为wordlist.txt的文件中最常见的前10个字长,该文件包含从a到z的所有单词。我编写了一个函数(名为'value_length'),它返回特定列表中每个单词的长度列表。我还应用了字典中的计数器模块(将单词长度作为键,将这些长度的频率作为值)来解决这个问题 from collections import Counter def value_length(seq): '''This function takes a sequence and retur

我正在编写一个函数,返回一个名为wordlist.txt的文件中最常见的前10个字长,该文件包含从a到z的所有单词。我编写了一个函数(名为'value_length'),它返回特定列表中每个单词的长度列表。我还应用了字典中的计数器模块(将单词长度作为键,将这些长度的频率作为值)来解决这个问题

from collections import Counter

def value_length(seq):
    '''This function takes a sequence and returns a list that contains 
    the length of each element
    '''
    value_l = []
    for i in range(len(seq)):
        length = len(seq[i])
        value_l.append(length)
    print(value_l) 

# open the txt file 
fileobj = open("wordlist.txt", "r")
file_content = []

# create a list with length of every single word   
for line in fileobj:
    file_content.append(line)
    wordlist_lengths = value_length(file_content)

# create a dictionary that has the number of occurrence of each length as key
occurrence = {x:file_content.count(x) for x in file_content}
c = Counter(occurrence)
c.most_common(10)  

但是每当我运行这段代码时,我都没有得到我想要的结果;我只从value_length函数(即一个非常长的列表,其中包含每个单词的长度)中获得结果。换句话说,Python不会解释字典。我不明白我的错误是什么。

不需要在列表中存储长度,也不需要使用列表的
计数方法;您已经导入了
计数器
,因此只需使用它进行计数即可

c=计数器()
对于以下文字:
长度=长度(字)
c[长度]+=1

此代码将找到每个列表项的长度并对其进行排序。然后,您可以简单地将列表中的发生次数+发生次数组成一个元组:

words = ["Hi", "bye", "hello", "what", "no", "crazy", "why", "say", "imaginary"]

lengths = [len(w) for w in words]
print(lengths)
sortedLengths = sorted(lengths)
print(sortedLengths)

countedLengths = [(w, sortedLengths.count(w)) for w in sortedLengths]
print(countedLengths)
这张照片是:

[2, 3, 5, 4, 2, 5, 3, 3, 9]
[2, 2, 3, 3, 3, 4, 5, 5, 9]
[(2, 2), (2, 2), (3, 3), (3, 3), (3, 3), (4, 1), (5, 2), (5, 2), (9, 1)]

您已经定义了
wordlist\u length=value\u length(文件内容)
,但是没有对
wordlist\u length执行任何操作。当然,这就是问题的原因?或者,你可以用dict代替元组,就像你的问题一样。或者添加第二步,将最终列表中的所有元组转换为键/值对。