这是我的解决方案导致错误.返回0
PS:我仍然喜欢修复我的代码:)
from collections import Counter
import string
def count_letters(word):
global count
wordsList = string.split(word)
count = Counter()
for words in wordsList:
for letters in set(words):
return count[letters]
word = "The grey old fox is an idiot"
print count_letters(word)
Run Code Online (Sandbox Code Playgroud)
Mat*_*ant 21
def count_letters(word):
return len(word) - word.count(' ')
Run Code Online (Sandbox Code Playgroud)
或者,如果您有多个要忽略的字母,则可以过滤字符串:
def count_letters(word):
BAD_LETTERS = " "
return len([letter for letter in word if letter not in BAD_LETTERS])
Run Code Online (Sandbox Code Playgroud)
pka*_*zak 11
使用sum函数简单解决:
sum(c != ' ' for c in word)
Run Code Online (Sandbox Code Playgroud)
它是一种内存有效的解决方案,因为它使用生成器而不是创建临时列表,然后计算它的总和.
值得一提的是c != ' '返回True or False值,它是类型的值bool,但是bool是子类型int,所以你可以总结bool值(True对应1并False对应0)
您可以使用以下mro方法检查固有情况:
>>> bool.mro() # Method Resolution Order
[<type 'bool'>, <type 'int'>, <type 'object'>]
Run Code Online (Sandbox Code Playgroud)
在这里,您可以看到它bool的子类型int是子类型object.
MattBryant的答案很好,但是如果你想要排除更多类型的字母而不仅仅是空格,它就会变得笨重.以下是您当前使用的代码的变体Counter:
from collections import Counter
import string
def count_letters(word, valid_letters=string.ascii_letters):
count = Counter(word) # this counts all the letters, including invalid ones
return sum(count[letter] for letter in valid_letters) # add up valid letters
Run Code Online (Sandbox Code Playgroud)
示例输出:
>>> count_letters("The grey old fox is an idiot.") # the period will be ignored
22
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
134312 次 |
| 最近记录: |