python - python 满足条件后从头开始迭代

标签 python

我有以下代码:

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

如何让我的循环再次从头开始?

最佳答案

您可以尝试以下方法(根据需要进行调整以适合您的代码):

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 循环不同的是,在 for 循环中,for i in letters (并且 i 连续获得了字母的值) , i 是一个简单的计数器,因此要访问给定的字母,您必须对其进行索引。即,字母[i]

关于python - python 满足条件后从头开始迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11678904/

相关文章:

python - 使用 Pandas 添加计算列

Python:如何从类所在的范围获取常量?

python - 恢复丢失的 multiprocessing.Queue 项目,当工作进程死亡时

python - 类型错误 : argument of type 'NoneType' is not iterable with mysql. 连接器

Python Flask - 重定向到带有查询结果的同一页面

Python 并发.futures : ProcessPoolExecutor fail to work

python - TensorFlow 数据集 .map() 方法不适用于内置 tf.keras.preprocessing.image 函数

python - 解析页面的所有输入标签

python - Vim 与 Python 3 : "Caught deadly signal ABRT glibc detected..." 一起崩溃

Python - 嵌套 ifs 的相同 else 代码