首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用循环中的函数返回值更新多个(局部变量)变量

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

Stack Overflow用户
提问于 2015-01-02 03:24:33
回答 1查看 841关注 0票数 1

假设我有以下(当前没有返回)函数:

代码语言:javascript
复制
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

如何最好地在这样定义的both循环中更新offsetoutput (即增量和追加)?:

代码语言:javascript
复制
def main():
    text = "\x0A\x0B\x0C\x01"
    offset = 0
    output = ''
    while offset < len(text):

我以前使用过两种方法:

1

代码语言:javascript
复制
def convert_codepoint(text, offset, output):
    # A: see first code snippet
    # B: concatenate to "output" (+=) instead of assigning (=)
    return [offset, output]

def main():
    text = "\x0A\x0B\x0C\x01"
    offset = 0
    output = ''
    while offset < len(text):
        offset, output = convert_codepoint(text, offset, output)

2

代码语言:javascript
复制
offset = 0 # global variable

def convert_codepoint(text, offset):
    global offset
    # A: see first code snippet
    return output

def main():
    text = "\x0A\x0B\x0C\x01"
    output = ''
    while offset < len(text):
        output += convert_codepoint(text, offset)

在我看来,第一种方法令人困惑,因为它似乎取代了offsetoutput变量,而不是更新它们,因为它使用=而不是+= (我似乎无法在列表中以某种方式使用+= --无论如何,在Python3.4.2中分配,因为它抛出了一个SyntaxError (“用于增广赋值的非法表达式”)。而且,使用list作为返回值似乎也不太方便端口。

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

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-01-02 03:54:06

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

代码语言:javascript
复制
def get_next_output_offset_pair(text, offset):
  #A: Adapt first code snippet
  return [next_offset, next_output]

def main():
   text = "\x0A\x0B\x0C\x01"
   offset = 0
   output = ''
   while offset < len(text):
     offset, next_output = get_next_output_offset_pair(text, offset)
     output.append(next_output)

或者,你甚至可以这么做

代码语言:javascript
复制
      next_offset, next_output = get_next_output_offset_pair(text, offset)
      output.append(next_output)
      offset = next_offset

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27737031

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档