Convert the following while loop into a for loop. Your code should be written so that the return statement does not need to be altered. You are allowed to change the code before the while loop proper. string_list is a list of string that contains at least 15 instances of the string
'***'
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)
这样的东西:
for i in range(15):
我不知道那是在做什么。
懒散版灵感来自彼得和阿斯蒂纳克斯的评论
我假设你是想写
string_list[j] == '***'
,而不是string_list[j] ='***'
。我还假设i
初始化为0
。第一步是了解循环实际上在做什么。它遍历
string_list
元素,每次遇到'***'
时,都会递增i
。当i
到达15
时,循环将终止,并且由于给定了string_list
至少包含'***'
的15个副本的前提条件,我们确实希望循环应该终止。当循环终止时,
i
将等于15
,并且j
将简单地计算列表中元素的数量直到现在。因此,首先,可以尝试如下迭代:
相关问题 更多 >
编程相关推荐