【发布时间】:2017-09-24 06:22:59
【问题描述】:
我正在尝试遍历 Python 中的列表,对其进行一些更改,然后输出结果。函数如下:
def scramble_bytes(self, ref_key):
"""
Uses ref_key as a reference to scramble self.
They must be equal-length lists of bytes
"""
if len(self) != len(ref_key):
return "Inputs to scramble_bytes must be equal length!"
scrambles_needed = range(len(self))
scramble_length = len(self)
output = self
for i in scrambles_needed:
scramble_selector = int.from_bytes(ref_key[i], byteorder='big')
scrambler_byte = int.from_bytes(output[(scramble_selector + i) % scramble_length], byteorder='big')
scrambled_byte = int.from_bytes(output[i], byteorder='big')
result_scramble = scrambler_byte ^ scrambled_byte
output[i] = result_scramble.to_bytes(1, byteorder="big")
return output
澄清一下,self 和 ref_key 都是字节列表,例如 [b'a', b'c', b'xb0']
我知道编辑一个在 Python 中循环的列表不是常见的做法,但在这种情况下我需要这样做,因为整个过程需要通过另一个仅获取 output 和 @ 的函数进行可逆处理987654326@ 作为其输入。如果我追加到一个新列表,该函数将不可逆。
我怀疑这个问题与 python 命名空间有关——output[i] 会在for 循环中创建一个新的局部变量。如果确实是这个问题,我该如何解决?
【问题讨论】:
标签: python for-loop namespaces