【问题标题】:Skipping iterations in a for loop when working with strings (in Python)使用字符串时跳过 for 循环中的迭代(在 Python 中)
【发布时间】:2021-12-10 16:44:25
【问题描述】:

我正在尝试编写一个使用字符串作为输入(句子或单词)的程序。使用 for 循环,我依次遍历每个字符。当我遇到字母 p 时,程序应该跳过几次迭代。我发现了很多关于在使用整数时跳过迭代的技巧。但是,在我的代码中,我正在使用字符串。有没有人对此有任何有用的提示?提前致谢!

这是我的一段改编代码(我目前拥有的):

language_input = input()

for character in language_input:

    if character == "p":
        # Now, I have to skip a few iterations (e.g. skip 3 characters)

【问题讨论】:

    标签: python string loops for-loop iterator


    【解决方案1】:

    这取决于您需要对字符串中的字符做什么。这是一个想法:

    language_input = input()
    i = 0
    while i < len(language_input):
        if language_input[i] == 'p':
            i += 3
        else:
            i += 1
            # do something else
    

    【讨论】:

    • 非常感谢您的回复!我认为我的代码现在正在做我想做的事情。感谢您的帮助! :)
    【解决方案2】:

    你可以使用一个额外的变量,如果设置了它什么也不做

    language_input = input()
    check = 0
    for character in language_input:
        if check:
            check -= 1
            continue
    
        if character == "p":
            check = 3 #set to number of iterations you want to skip
    
    

    【讨论】:

    • 感谢您的建议。这是一个很好的建议。我使用了其他人的建议,但是使用您的代码也可以解决问题,谢谢! :)
    【解决方案3】:

    你可以使用迭代器:

    language_input = 'abcdefghij'
    s = iter(language_input)
    while True:
        try:
            character = next(s)
            if character == 'd':
                print('…', end='')
                next(s)
                next(s)
                next(s)
            print(character, end='')
        except StopIteration:
            break
    

    输出:abc…dhij

    为了更有效地跳过许多项目,您可以使用itertools.islice

    from itertools import islice
    
    # … only showing changed part of code
    if character == 'd':
        print('…', end='')
        list(islice(s, 3)) # get 3 elements at once
    # …
    

    【讨论】:

    • 感谢您的精彩解释。我从未使用过 itertools 模块,我一定会尝试一下。感谢您提出此解决方案。
    猜你喜欢
    • 1970-01-01
    • 2021-08-23
    • 2021-11-15
    • 1970-01-01
    • 2023-03-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多