找一个句子中的字母数?

时间:2015-06-17 17:31:19

标签: python python-3.x

我正在尝试编写一个程序来查找句子中的字母总数。我想知道为什么我的程序错了。这就是我试过的:

words = ["hi", "how", "are", "you"]

alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]

y = 0

for i in words:
    for x in alphabet:
        n = words.count(x)
        y = y + n
print (y)

这个程序只返回4个零。

从我的角度来看,该程序应该像这样运行: 在循环的第一次运行中,i =" hi"和x =" a" 。 " a"的数量存储在变量n中,然后存储在变量y中。然后x取值" b"," c"等等,直到它贯穿整个字母表。然后重复下一件事,直到我转到第二个单词。

4 个答案:

答案 0 :(得分:3)

您的计划无效的原因是 - 您正在将words与每个单词i进行迭代,但在内循环中,您正在执行words.count()而不是i.count() }。

这就是你的for循环应该是这样的 -

for i in words:
    for x in alphabet:
        n = i.count(x)
        y = y + n
print (y)

答案 1 :(得分:2)

更改

n = words.count(x)

n = i.count(x)

诀窍。

<强>原因

您说i是每次迭代中的一个单词。因此,您必须使用i.count(x)来计算xi的数量

答案 2 :(得分:1)

我认为你应该使用n = i.count(x),而不是&#34; n = words.count(x)&#34;

words = ["hi", "how", "are", "you"]

alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]

y = 0

for i in words:
    for x in alphabet:
        n = i.count(x)
        y = y + n

print (y)

输出

11

答案 3 :(得分:-1)

sentence = "hi how are you"
count = sum(1 for c in sentence if c.isalpha())