将while循环转换为for循环

2024-04-25 08:45:12 发布

您现在位置:Python中文网/ 问答频道 /正文

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<15i = i+1时,我知道我的范围是(0…15),不包括15,所以基本上我们会有像i = range(15)这样的东西:

for i in range(15):

我不知道那是在做什么。


Tags: ofthetoloopconvertforstringreturn
2条回答
j = [i for i,x in enumerate(string_list) if x=='***'][15]
return j

懒散版灵感来自彼得和阿斯蒂纳克斯的评论

from itertools import islice
j = next(islice((i for i,x in enumerate(string_list) if x=='***'), 15, None))
return j

我假设你是想写string_list[j] == '***',而不是string_list[j] ='***'。我还假设i初始化为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个副本的前提条件,我们确实希望循环应该终止。

当循环终止时,i将等于15,并且j将简单地计算列表中元素的数量直到现在。

因此,首先,可以尝试如下迭代:

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

相关问题 更多 >