Python 保存函数返回的空列表
这就是我要求做的:Python 保存函数返回的空列表,python,Python,这就是我要求做的: 保存朋友(文件名,朋友列表)获取文件名和朋友列表,并将该列表以正确格式写入文件。那么比如说,, 保存朋友('friends.csv',加载朋友('friends.csv')) 应该用完全相同的内容覆盖friends le 这是我的代码: def save_friends(filename, friends_list): """ take a file name and a friends list and wrients that list to t
保存朋友(文件名,朋友列表)
获取文件名和朋友列表,并将该列表以正确格式写入文件。那么比如说,,
保存朋友('friends.csv',加载朋友('friends.csv'))
应该用完全相同的内容覆盖friends le
这是我的代码:
def save_friends(filename, friends_list):
"""
take a file name and a friends list and wrients that list
to the file in the correct format
save_friend(file, list) -> list
"""
friends_list = []
f = open(filename, 'w')
for friend in friends_list:
f.write(friend+ '\n')
return friends_list
f.close()
问题是当我运行文本代码(学校提供的代码,用于一些简单的测试)时,它会告诉我
>>>save_friends('friends_output.csv', d)
[ ]
Traceback (most recent call last):
File "E:\study\Yr 1\Semister1\CSSE1001\Assignment\sample_tests.py", line 84, in <module>
assert res == None, "save_friends didn't return None"
AssertionError: save_friends didn't return None
>>保存好友('friends\u output.csv',d)
[ ]
回溯(最近一次呼叫最后一次):
文件“E:\study\Yr 1\Semister1\CSSE1001\Assignment\sample\u tests.py”,第84行,在
assert res==None,“save\u friends没有返回None”
AssertionError:save_friends没有返回None
那么,当输入不是一个真正的列表(在这种情况下像输入“d”)时,我怎么能返回“None”?将
朋友列表
参数替换为函数顶部的一个空列表:
friends_list = []
拆下那条线
此外,函数不应返回任何内容;您还需要删除return
行才能通过赋值测试,该测试要求函数中的None
(默认设置)
请注意,通过提前返回,您也不会对文件调用
.close()
。还应删除返回朋友列表
行,否?我不知道他想做什么。一方面,他想返回一个列表,另一方面,一个都没有。@camelNeck:函数的规范没有说明返回列表的任何内容——我很确定这是源于start@camelNeck当前位置作业说明没有说明他需要返回列表,只有他的docstring需要返回列表。任务测试回溯显示他返回列表是错误的。我认为你的基本问题是你不知道你的函数应该做什么。在这种情况下,我认为您不应该返回任何内容,因为列表不会更改。您在此处发布的代码中存在语法错误,复制到此处的代码将无法运行。循环行的上缺少一个空格。假设您的实际代码没有这个错误,否则您甚至不会得到AssertionError
。