Python中如何通过辅助函数获取列表待修改值的地址并完成赋值
方案1:路径元组+通用读写函数
Python不支持直接对函数返回值赋值,你可以让定位函数返回目标元素所属的容器、以及完整索引路径的元组,配合两个通用读写函数实现类似指针的操作:
# 通用读函数 def get_ref(ref): container, *indices = ref for idx in indices: container = container[idx] return container # 通用写函数 def set_ref(ref, new_val): container, *indices = ref for idx in indices[:-1]: container = container[idx] container[indices[-1]] = new_val
各场景使用示例
一维列表修改:
helper = lambda x: (x, 0) a = [1, 2, 3] set_ref(helper(a), 0) # a 变为 [0, 2, 3]
二维列表修改:
helper_1 = lambda x: (x, 0, 0) a = [[1, 2, 3]] set_ref(helper_1(a), 0) # a 变为 [[0, 2, 3]]
90度旋转实现(完全消除冗余索引写法):
def rotate_90(image, direction): rows, columns = len(image), len(image[0]) rotated = [[0]*rows for _ in range(columns)] # 定位函数直接返回路径元组 if direction == 'R': rotated_place = lambda row, col: (rotated, col, -1 - row) else: rotated_place = lambda row, col: (rotated, -1 - col, row) for row in range(rows): for col in range(columns): set_ref(rotated_place(row, col), image[row][col]) return rotated
方案2:封装引用类,更贴近指针语法
如果你希望写法更接近C风格指针语法,可以封装一个简单的引用类,通过属性读写实现赋值:
class Ref: def __init__(self, container, *indices): self.container = container self.indices = indices @property def val(self): res = self.container for idx in self.indices: res = res[idx] return res @val.setter def val(self, new_val): res = self.container for idx in self.indices[:-1]: res = res[idx] res[self.indices[-1]] = new_val
各场景使用示例
一维列表修改:
helper = lambda x: Ref(x, 0) a = [1, 2, 3] helper(a).val = 0
遍历修改一维列表:
lst = [1, 2, 3] for i in range(len(lst)): ref = Ref(lst, i) ref.val *= 2 # lst 变为 [2, 4, 6]
90度旋转实现:
def rotate_90(image, direction): rows, columns = len(image), len(image[0]) rotated = [[0]*rows for _ in range(columns)] if direction == 'R': rotated_place = lambda row, col: Ref(rotated, col, -1 - row) else: rotated_place = lambda row, col: Ref(rotated, -1 - col, row) for row in range(rows): for col in range(columns): rotated_place(row, col).val = image[row][col] return rotated
以上两种方案都是纯Python原生实现,不需要引入额外依赖,完全符合Python的语法规则,同时可以避免多层索引写法的冗余问题。
内容的提问来源于stack exchange,提问作者gil aharoni
相关产品推荐
相关产品推荐

