将while循环转换为for循环 [英] Converting while loops into for loops
问题描述
将以下while循环转换为for循环.应该编写您的代码,以便不需要更改return语句.您可以在while循环之前更改代码.string_list是一个字符串列表,其中包含至少15个字符串
'***'
j=0
while i<15:
if string_list[j] ='***':
i +=1
j +=1
return j
我首先尝试这样做,它说而 i< 15
和 i = i + 1
,所以我知道我的范围是(0 ... 15),不包括15所以基本上我们会像 i = range(15)
这样,我们会有类似的东西:
I tried doing this first it says while i<15
and i = i+1
so i know i ranges from (0...15) not including 15 so basically we will have like i = range(15)
so we will have something like:
for i in range(15):
我不知道那个 j
在做什么.
I don't know what that j
is doing there.
推荐答案
我假设您要编写 string_list [j] =='***'
而不是 string_list [j] ='***'
.我还将假设 i
初始化为 0
.
I will assume you meant to write string_list[j] == '***'
instead of string_list[j] ='***'
. I will also assume i
is initialised to 0
.
i, j = 0, 0
while i < 15:
if string_list[j] == '***':
i += 1
j += 1
return j
第一步是了解循环的实际作用.它遍历 string_list
元素,并且每次遇到'***'
时, i
都会递增.当 i
达到 15
时,循环将终止,并且由于前提是 string_list
包含至少15个'**的副本*'
我们确实希望循环会终止.
The first step is to understand what the loop is actually doing. It is iterating through string_list
elements, and every time an '***'
is encountered, i
is incremented. The loop will terminate when i
reaches 15
, and since a precondition was given that string_list
contains at least 15 copies of '***'
we do expect the loop should terminate.
当循环终止时, i
等于 15
,而 j
只会计算列表中的元素数量,直到这点.
When the loop terminates, i
will be equal to 15
and j
will simply have counted the number of elements in the list up until this point.
因此,从头开始,您可以尝试像这样进行迭代:
So to start you off, you could try iterating like this:
for s in string_list:
if s == `***`:
# keep track of how many times this has happened
# break if you've seen it happen 15 times
j += 1
return j
这篇关于将while循环转换为for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!