Python:转换一个';对于';循环为while循环,但它必须满足循环中的len(i)条件
我一直在练习用Python:转换一个';对于';循环为while循环,但它必须满足循环中的len(i)条件,python,while-loop,Python,While Loop,我一直在练习用切换循环,而用Python切换循环 我的问题是while循环下的一行,我试图检查I(字符串句子中的一个单词)是否短于六个字符。对于for循环,这很容易,因为它只是在单词中迭代每个单词,所以我可以使用len(I),但是在中,而版本I现在是int,所以我该怎么办 对于循环版本: def concatenation(string): words = string.split() result = '' for i in words: if len(
切换循环,而用Python切换循环
我的问题是while循环下的一行,我试图检查I
(字符串句子中的一个单词)是否短于六个字符。对于for
循环,这很容易,因为它只是在单词中迭代每个单词,所以我可以使用len(I)
,但是在中,而版本I
现在是int,所以我该怎么办
对于循环版本:
def concatenation(string):
words = string.split()
result = ''
for i in words:
if len(i) < 6:
result = result + i
return result
当你写的时候,你已经部分地得到了它
if len(words[i]) < 6:
测试用例:
>>> a = "this is a test string, alright yeah?"
>>> concat_while(a)
'thisisatestyeah?'
当你写的时候,你已经部分地得到了它
if len(words[i]) < 6:
测试用例:
>>> a = "this is a test string, alright yeah?"
>>> concat_while(a)
'thisisatestyeah?'
i
在while循环中从不更改,因此您永远不会到达它的终点。无论如何,在这两个示例中,您在不同的上下文中使用i
。根据变量代表的内容命名变量是一种很好的做法。更好的例子:
例如循环(与word
互换i
):
i
在while循环中从不更改,因此您永远不会到达它的终点。无论如何,在这两个示例中,您在不同的上下文中使用i
。根据变量代表的内容命名变量是一种很好的做法。更好的例子:
例如循环(与word
互换i
):
对不起,Craig,我只是在提交后编辑它来添加我的I+=1增量,意识到我忘了添加I增量。对不起Craig,我只是在提交后编辑它来添加我的I+=1增量,意识到我忘了添加I增量。非常感谢!我现在完全明白了——我想我的len(words[I])已经关闭了,所以我没有想到我所在的下一行应该是words[I],因为我在上面一行收到了错误消息。非常感谢。是的,关于i递增器,我很抱歉-我在提交后意识到我忘记了那个部分。我在那上面的缩进也错了。非常感谢!我现在完全明白了——我想我的len(words[I])已经关闭了,所以我没有想到我所在的下一行应该是words[I],因为我在上面一行收到了错误消息。非常感谢。是的,关于i递增器,我很抱歉-我在提交后意识到我忘记了那个部分。我在这一点上的缩进也错了。这是个好主意-我通常使用“for words in words”来解决句子问题,但当我尝试while循环时,将其称为“word”似乎有些奇怪,但您使用名称words_索引的示例现在对我来说很有意义。这是个好主意-我通常使用“for words in words”来解决句子问题,但是当我尝试while循环时,将其称为“word”似乎有些奇怪,但是您使用words\u索引的示例现在对我来说是有意义的。
def concatenation(string):
words = string.split()
result = ''
for word in words:
if len(word) < 6:
result += word
return result
def concatenation(string):
words = string.split()
result = ''
words_index = 0
while words_index < len(words):
word = words[words_index]
if len(word) < 6:
result += word
words_index += 1
return result