2012-03-27 124 views
1

在python中,我將如何計算一個單詞中輔音的數量?我意識到有幾種不同的方法可以做到這一點,但我認爲我選擇的方式是分析每個字母的字母,並在遇到輔音時添加到櫃檯。我無法弄清楚如何實現它。我如何計算一個單詞中輔音的數量? python

從這開始的東西?

count = 0 
consonant = 'astringofconsonants' 
if consonant in string[0]: 
    count += 1 
+1

謝謝大家,你的回答給了我一些想法。 – user1294377 2012-03-27 04:04:56

回答

0

你給的開始不是很Python的。

試圖通過列表迭代使用

for c in word: 
    if c in consonants: 
     # do something 

你也可以使用類似下面的發電機。它會通過每個字母並計算每個輔音的數量。

(word.count(c) for c in consonants) 

使用sum()功能將它們全部加起來

+0

說到pythonic,我認爲你的意思是'list',而不是'array';) – Blender 2012-03-27 04:03:57

+0

ahhh yes對不起,混淆其他語言 – jamylak 2012-03-27 04:05:39

+0

我總是讀「Pythonic」爲「遠不適合初學者」:-) – paxdiablo 2012-03-27 04:18:10

2

您可以通過遍歷字符串你遍歷列表以同樣的方式:

for letter in word: 
    if letter in consonants: 
    # You can fill in from here 
1

遍歷字符串產生依次在每個字符。

for c in 'thequickbrownfoxjumpsoverthelazydog': 
    print c 
+0

這就是我需要的所有工作,謝謝大家! – user1294377 2012-03-27 04:04:27

1

理解!

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']) 
+0

這實際上不是一個(Python)理解。 – 2012-03-27 04:01:33

+0

或者爲什麼不只是,len([c對於c中的單詞如果不在['a','e','i','o','u']]) – kwarrick 2012-03-27 04:02:02

+0

我會用'' aeiou'':'count = len([如果字母不在'aeiou'中,則爲字母中的字母]]' – Blender 2012-03-27 04:02:28

相關問題