我正在研究一些例子,我必须将'for'循环转换为'while'循环,这个让我感到难过。对我来说问题是'for'循环完美地设计为遍历字符串中的每个字符,然后该字符可以很容易地转换为'ord'以获取其ASCII代码。但是当我尝试检索“ord”部分时,将其转换为“while”循环会给我带来问题。我尝试使用split()并尝试使用索引查找每个字母,但到目前为止它还没有工作。
请注意,代码本身只是垃圾代码,不会产生任何有用的东西 - 它纯粹只是为了练习'while'循环。谢谢!
提供的问题转换为'while'循环:
def convert(string):
"""take string and return an int that is the unicode version"""
num = 0
for char in string:
if ord(char) > 20:
num = ord(char) - 10
else:
num = ord(char) * 2
return num
print(convert('Test this string'))
我尝试'while'循环版本:
def convert(string):
"""take string and return an int that is the unicode version"""
char_value = string.split()
num = 0
char_index = 0
while char_index < len(string):
if ord(char_value[char_index]) > 20:
num = char_value - 10
else:
num = char_value * 2
char_index += 1
return num
print(convert('Test this string'))
编辑:这是在NPE的建议之后调整的工作解决方案(以防初学者希望看到完整的解决方案):
def convert(string):
"""take string and return an int that is the unicode version"""
num = 0
char_index = 0
while char_index < len(string):
char = string[char_index]
if ord(char) > 20:
num = ord(char) - 10
else:
num = ord(char) * 2
char_index += 1
return num
print(convert('Test this string'))
你不需要使用split
。您可以使用字符索引直接索引字符串。
将for
重写为while
的简单方法如下所示:
char_index = 0
while char_index < len(string):
char = string[char_index]
...
char_index += 1
(...
部分可以与for
循环的主体完全一样。)
我会提出一种更优雅,甚至更等效的方法来编写循环:
def convert(string):
"""take string and return an int that is for sure not any kind of Unicode version, whatever that's supposed to be"""
it = iter(string)
while True:
char = next(it, None)
if char is None:
break
if ord(char) > 20:
num = ord(char) - 10
else:
num = ord(char) * 2
return num
print(convert('Test this string'))
你可能会问,为什么迭代器的方法更优雅。一些简单的原因: