通过循环中的函数返回值更新多个(局部)变量



假设我有这个(当前无返回)函数:

def codepoint_convert(text, offset):
    codepoint = text[offset]
    if codepoint <= 0x01:
        output = "n"
    elif codepoint >= 0x09 and codepoint <= 0x12: # digits
        output = chr(0x30 + (codepoint-0x09))
    elif codepoint >= 0x13 and codepoint <= 0x2C: # uppercase letters
        output = chr(0x41 + (codepoint-0x13))
    elif codepoint >= 0x2D and codepoint <= 0x46: # lowercase letters
        output = chr(0x61 + (codepoint-0x2D))
    elif codepoint >= 0x47 and codepoint <= 0x62: # multi-byte codepoints
        offset += 1
        codepoint = (codepoint << 8) + text[offset]
        output = cp_dict[codepoint]
    else:
        print("Invalid codepoint at 0x%08X" % offset)
    offset += 1

我将如何在这样定义的 while 循环中最好地更新(即分别递增和追加)offsetoutput

def main():
    text = "x0Ax0Bx0Cx01"
    offset = 0
    output = ''
    while offset < len(text):

我以前使用过两种方法:

1

def convert_codepoint(text, offset, output):
    # A: see first code snippet
    # B: concatenate to "output" (+=) instead of assigning (=)
    return [offset, output]
def main():
    text = "x0Ax0Bx0Cx01"
    offset = 0
    output = ''
    while offset < len(text):
        offset, output = convert_codepoint(text, offset, output)

阿拉伯数字

offset = 0 # global variable
def convert_codepoint(text, offset):
    global offset
    # A: see first code snippet
    return output
def main():
    text = "x0Ax0Bx0Cx01"
    output = ''
    while offset < len(text):
        output += convert_codepoint(text, offset)

对我来说,第一种方法令人困惑,因为它看起来像是替换了offsetoutput变量而不是更新它们,因为它使用 = 而不是 +=(无论如何,我似乎无法以某种方式在 Python 3.4.2 的列表赋值中使用+=,因为它抛出了一个SyntaxError("用于增强赋值的非法表达式"))。使用列表作为返回值似乎也不是那么适合端口。

我对第二种方法的抱怨是它使用全局变量。我希望可以调用convert_codepoint()(例如,如果脚本作为模块导入),而不必定义全局变量。offset变量可能也需要从main函数重新初始化,因此可能会变得混乱。

我可以尝试任何其他方法,以一种漂亮而清晰的方式在本地更新变量?

为什么不有一个返回下一个输出和偏移量的函数,然后将下一个输出元素附加到输出列表中:

def get_next_output_offset_pair(text, offset):
  #A: Adapt first code snippet
  return [next_offset, next_output]
def main():
   text = "x0Ax0Bx0Cx01"
   offset = 0
   output = ''
   while offset < len(text):
     offset, next_output = get_next_output_offset_pair(text, offset)
     output.append(next_output)

或者,您甚至可以这样做:

      next_offset, next_output = get_next_output_offset_pair(text, offset)
      output.append(next_output)
      offset = next_offset

我认为你的第一个解决方案非常清楚,但你的代码应该对来说很直观,而不会让下一个维护者的生活变得困难。

最新更新