【问题标题】:For loop in range incrementation范围递增中的for循环
【发布时间】:2021-06-12 18:32:37
【问题描述】:

为什么for循环中的“c”不递增?

def solution(s):
    for c in range(len(s)):
        if s[c] == s[c].upper():
            s = s[:c] + ' ' + s[c:]
            c += 1
    return s
print(solution('helloWorld'))

输出应该是"hello World",但是,当我添加一个空格" " 时,我也会增加c,但它不起作用。 当前输出为'hello World'

【问题讨论】:

  • 你的意思是print(solution("helloWorld"))?
  • 是的,我的错误,但它仍然无法正常工作
  • 请edit问题反映这一点。顺便说一句,欢迎来到 Stack Overflow!如果需要提示,请查看tour 和How to Ask。

标签: python python-3.x for-loop


【解决方案1】:

你可以想到:

for c in range(len(s)):

因为c 在每次循环迭代时都被范围“设置”。该范围会跟踪它所处的迭代次数。

我认为你的意思是这样的:

def solution(s):
    c = 0
    while c < len(s):
        if s[c] == s[c].upper():
            s = s[:c] + ' ' + s[c:]
            c += 1
        c += 1
    return s

【讨论】:

    【解决方案2】:

    发生这种情况是因为c 在下一次迭代for c in ... 时自动重新设置。通常,当您在迭代时尝试修改某些内容时,您会遇到此问题,因为索引不会匹配。 Here's another example.

    您可以改用while 循环,但实际上,构建新的输出字符串更容易:

    def solution(s):
        out = ''
        for c in s:
            if c.isupper():  # I also simplified this
                out += ' '
            out += c
        return out
    
    print(solution("helloWorld"))  # -> hello World
    

    不过,最好使用str.join() 来构建字符串,例如使用generator expression:

    def solution(s):
        return ''.join(' '+c if c.isupper() else c for c in s)
    
    print(solution("helloWorld"))  # -> hello World
    

    【讨论】:

      【解决方案3】:

      是的,因为您没有调用该函数。

      【讨论】:

      • 这似乎是一个错字,因为 OP 写了“当前输出是 'hello World'”,这实际上是你运行函数得到的结果
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-03
      • 1970-01-01
      • 2019-02-07
      • 2022-12-16
      • 1970-01-01
      相关资源
      最近更新 更多