如何用while循环替换for

时间:2012-10-20 05:13:16

标签: python

如何将for循环更改为while循环。使用forwhile循环有什么显着差异?

S="I had a cat named amanda when I was little"
count = 0
for i in S:
    if i =="a":
        count += 1
print (count)

3 个答案:

答案 0 :(得分:3)

以下是相同代码的while循环实现。

i = 0
count = 0
while i < len(S):
    if S[i] == 'a':
        count += 1
    i += 1
print count

答案 1 :(得分:1)

你需要一个计数器,每次“计数器&lt; len(S)”

时都会递增

这是一个开始:

index = 0
count = 0
while index < len(S):
    #do something with index and S ...
    index += 1

答案 2 :(得分:0)

您也可以通过空字符串/列表/字典的布尔特性来完成。

S="I had a cat named amanda when I was little"
count = 0
while S:
    # pop the first character off of the string
    ch, S = S[0], S[1:]
    if ch == "a":
        count += 1
print (count)