1

我正在研究必须将“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'))
4

2 回答 2

2

你不需要使用split. 您可以使用字符索引直接对字符串进行索引。

一种直接重写foras a 的while方法如下所示:

    char_index = 0
    while char_index < len(string):
        char = string[char_index]
        ...
        char_index += 1    

(该...部分可以完全作为for循环的主体。)

于 2018-09-08T04:18:01.630 回答
1

我会提出一种更优雅甚至更等效的方式来编写该循环:

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'))

您可能会问,为什么迭代器方法更优雅。几个简单的原因:

  • 这适用于任何序列,即使是不可索引的序列。
  • 您不必提前计算序列的长度,为什么可能需要先将其加载到内存中。
  • 您可以将其与长度无限的序列(此特定算法将无限循环)或长度未知的序列一起使用(想想用户输入)。
于 2018-09-08T06:11:24.507 回答