[英]Python dictionary being returned
I'm trying to create dictionary with the count of each letter appearing in a list of words. 我正在尝试创建字典,使每个字母的计数出现在单词列表中。 The method count_letters_v2(word_list)
, print the letters but does not return the dictionary. 方法count_letters_v2(word_list)
,打印字母,但不返回字典。 Why? 为什么? And how do I fix this? 我该如何解决呢? Thank you. 谢谢。
def count_letters_v2(word_list):
count = {}
for word in word_list:
print word
for letter in word:
print letter
if letter not in count:
count[letter] = 1
else:
count[letter] = count[letter] + 1
return count
def main():
count_letters_v2(['a','short','list','of','words'])
if __name__ == '__main__':
main()
It does return the dictionary. 它确实返回字典。 That's what return count
does. 那就是return count
作用。 Do you want to print out the dictionary? 您要打印字典吗? Then change main()
to 然后将main()
更改为
def main():
print count_letters_v2(['a','short','list','of','words'])
For the record, there's a Counter
object (a subclass of dict
so can do all the same things) in the standard library that will do this all for you. 作为记录,标准库中有一个Counter
对象( dict
的子类,因此可以做所有相同的事情),将为您完成所有操作。
from collections import Counter
def count_letters_v3(word_list):
return Counter(''.join(word_list))
print count_letters_v3(['a','short','list','of','words'])
Output: 输出:
Counter({'a': 1,
'd': 1,
'f': 1,
'h': 1,
'i': 1,
'l': 1,
'o': 3,
'r': 2,
's': 3,
't': 2,
'w': 1})
As said, you code works but you didn't do anytinhg with the return value of the function. 如前所述,您的代码可以工作,但是您对函数的返回值没有任何反应。
That said, I can think of some improvements though. 也就是说,我可以想到一些改进。 First, the get
method of dict
will make the case of a new letter cleaner, setting the default value to 0
: 首先, dict
的get
方法将使新字母更加清晰,将默认值设置为0
:
...
count = {}
for word in word_list:
for letter in word:
count[letter] = count.get(letter, 0) + 1
...
Otherwise, you can use a Counter
object from collections: 否则,您可以使用集合中的Counter
对象:
from collections import Counter
def count_letters_v2(word_list):
count = Counter()
for word in word_list:
count.update(word)
return count
If you have a very long list of words, you shouldn't use str.join
since it builds new string. 如果单词列表很长,则不应使用str.join
因为它会生成新的字符串。 The chain_from_iterable
method of itertools
module will chain the letters for free: itertools
模块的chain_from_iterable
方法将免费链接字母:
from collections import Counter
from itertools import chain
def count_letters_v2(word_list):
return Counter(chain.from_iterable(word_list))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.