假设我有以下(当前没有返回)函数:
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循环中更新offset和output (即增量和追加)?:
def main():
text = "\x0A\x0B\x0C\x01"
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 = "\x0A\x0B\x0C\x01"
offset = 0
output = ''
while offset < len(text):
offset, output = convert_codepoint(text, offset, output)2
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)在我看来,第一种方法令人困惑,因为它似乎取代了offset和output变量,而不是更新它们,因为它使用=而不是+= (我似乎无法在列表中以某种方式使用+= --无论如何,在Python3.4.2中分配,因为它抛出了一个SyntaxError (“用于增广赋值的非法表达式”)。而且,使用list作为返回值似乎也不太方便端口。
我对第二种方法的不满是,它使用了一个全局变量。我希望能够调用convert_codepoint() (例如,如果脚本作为模块导入),而不必定义全局变量。offset变量可能也需要从main函数重新初始化,这样就会变得很混乱。
我可以尝试的任何其他方法,在本地更新变量,以一种很好和清晰的方式?
发布于 2015-01-02 03:54:06
为什么不使用一个函数返回下一个输出和偏移量,然后将下一个输出元素追加到输出列表中:
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)或者,你甚至可以这么做
next_offset, next_output = get_next_output_offset_pair(text, offset)
output.append(next_output)
offset = next_offset我认为您的第一个解决方案非常清楚,但是您的代码对您来说应该是直观的,而不会使下一个维护者的生活变得困难。
https://stackoverflow.com/questions/27737031
复制相似问题