Python:是否更改函数内部的dict

2024-05-15 22:11:38 发布

您现在位置:Python中文网/ 问答频道 /正文

假设有一个任务-在dict中做一些更改 例如,我们有dict:{faculty: [students]}模拟大学目录,我们得到扣除列表-[student_1, student_2, ...],我们想从该列表中扣除所有学生。 哪种方式更像Python:

  1. 编写函数更改函数内部的dict
def deducation(students, deducation_list):
  # deducate students
  # return nothing

students = {faculty: [students]}
deducation_list = [student_1, student_2, ...]
deducation(students, deducation_list)

2.编写在自身内部生成dict并返回新dict的函数

def deducation(students, deducation_list):
  new_students = dict()
  # deducate students
  return new_students

students = {faculty: [students]}
deducation_list = [student_1, student_2, ...]
students = deducation(students, deducation_list)

比较: 第一路

“+”:内存成本更低(没有新的dict生成内部函数),更紧凑

“-”:函数内部不明显的转换(通常您不会期望该函数会更改内部对象)>;代码可读性较差

第二条路

“+”:代码更具可读性

“-”:内存成本更高-内部创建的新dict可以更高 内部复杂的逻辑生成新的

所以问题是-哪种方式更适合哪种情况?


Tags: 函数内存列表newreturndef方式student