我想根据学科将学生分为两个不同的列表,但是该功能无法创建不同的列表。我知道在这两种情况下创建的列表的实例都是相同的,但是我找不到相同的可行解决方案。
def add_tolist(name, students=[]):
students.append(name)
return students
idc306 = add_tolist('ram')
idc101 = add_tolist('shyam')
idc101 = add_tolist('deepa',idc101)
print idc101, idc306
结果应为: ['shyam','deepa'] ['ram']
但是它的印刷: ['ram','shyam','deepa'] ['ram','shyam','deepa']
答案 0 :(得分:0)
我认为问题在于您的程序将新列表视为不是单独的新副本,这将解决该问题。
def add_tolist(name, students=[]):
students1 = students.copy()
students1.append(name)
return students1
idc306 = add_tolist('ram')
idc101 = add_tolist('shyam')
idc101 = add_tolist('deepa',idc101)
print (idc101, idc306)
输出:['shyam','deepa'] ['ram']