如何在保留zip用法的前提下替换连续元素配对函数中的eval语句
解决方案
核心思路是利用Python的可变位置参数解包语法*,直接把构造好的所有切片序列作为独立参数传入zip,完全替代eval动态拼接参数的逻辑,全程保留zip的使用,无需任何动态代码执行。
修改后的完整代码如下:
def consecutive_element_pairing(data: list[int], consecutive_element=3, map_to_func=sum) -> list[int]: """ Return a list with consecutively paired items given to a function that can handle an iterable :param data: the list of integers to process :param consecutive_element: how many to group consecutively :param map_to_func: the function to give the groups to :return: the new list of consecutive grouped functioned items """ if len(data) < consecutive_element: return [] # 用解包替代eval,把所有切片作为独立参数传入zip return list(map(map_to_func, zip(*[data[i:] for i in range(consecutive_element)])))
代码说明
你原来用eval拼接参数的本质是要给zip传入n个独立的切片参数,即zip(data[0:], data[1:], data[2:], ..., data[n-1:])。现在我们用列表推导式先生成包含所有切片的列表[data[0:], data[1:], ..., data[n-1:]],再通过*运算符把列表中的每个元素作为独立的位置参数传给zip,运行效果和你原来的实现完全一致。
用你给出的示例测试:
values = [1, 2, 3, 4, 5, 6, 7, 8, 9] print("result:", consecutive_element_pairing(values))
输出依然是:[6, 9, 12, 15, 18, 21, 24],和原有实现结果完全匹配。
这个方案不仅彻底去掉了风险较高的eval语句,代码可读性、执行效率也比动态生成代码的方案更好。
内容的提问来源于stack exchange,提问作者Ivonet
相关产品推荐
相关产品推荐

