在python中,我將如何計算一個單詞中輔音的數量?我意識到有幾種不同的方法可以做到這一點,但我認爲我選擇的方式是分析每個字母的字母,並在遇到輔音時添加到櫃檯。我無法弄清楚如何實現它。我如何計算一個單詞中輔音的數量? python
從這開始的東西?
count = 0
consonant = 'astringofconsonants'
if consonant in string[0]:
count += 1
在python中,我將如何計算一個單詞中輔音的數量?我意識到有幾種不同的方法可以做到這一點,但我認爲我選擇的方式是分析每個字母的字母,並在遇到輔音時添加到櫃檯。我無法弄清楚如何實現它。我如何計算一個單詞中輔音的數量? python
從這開始的東西?
count = 0
consonant = 'astringofconsonants'
if consonant in string[0]:
count += 1
你給的開始不是很Python的。
試圖通過列表迭代使用
for c in word:
if c in consonants:
# do something
你也可以使用類似下面的發電機。它會通過每個字母並計算每個輔音的數量。
(word.count(c) for c in consonants)
使用sum()
功能將它們全部加起來
您可以通過遍歷字符串你遍歷列表以同樣的方式:
for letter in word:
if letter in consonants:
# You can fill in from here
遍歷字符串產生依次在每個字符。
for c in 'thequickbrownfoxjumpsoverthelazydog':
print c
這就是我需要的所有工作,謝謝大家! – user1294377 2012-03-27 04:04:27
理解!
count = sum(1 for c in cons if c not in ['a','e','i','o','u'])
從評論,或許更Python:
count = len([c for c in cons if c not in 'aeiou'])
謝謝大家,你的回答給了我一些想法。 – user1294377 2012-03-27 04:04:56