我有以下代码:
letters = 'abcdefg'
for i in letters:
if ...
#condition that tests something I need
#once condition is satisfied, something is done, the condition is modified
# and letters becomes:
letters = letters.replace(i,'')
### Now I want to start this for loop again because my condition
### may now be met with the initial letters
如何让我的循环从头开始?
答案 0 :(得分:2)
您可以尝试这些方法(根据需要进行调整以适合您的代码):
i = 0
while i < len(letters):
if ....
letters = letters.replace(letters[i], '') # probably what you want
i = 0
else:
i += 1
循环中的迭代由i
的值控制。只要i
小于字符串(7)的长度,它就会保持循环,每次在循环中递增i
(用作计数器)的值。当您设置i = 0
时,您将重新启动计数器。
注意与for-loop不同的是for i in letters
(并且i
连续获得了一个字母的值),i
很简单计数器,所以要访问给定的字母,你必须索引它。即,letters[i]
答案 1 :(得分:0)
这样的事情可能会满足你的需求:
while letters and not breakCondition:
for i in letters:
if someLogic():
letters = letters.replace(i, '')
break