我应该运行文件assign2_partI_test_file
并获得以下结果。我无法得到正确的结果。
我的代码:
def to_string(my_list, sep=', '):
result = ' '
msg = 'List is: '
for char in my_list:
str_list1 = ['r', 'i', 'n', 'g', 'i', 'n', 'g']
if my_list == str_list1:
result = msg + sep.join(my_list)
return result
我的输出:
Start testing!
length Test
Start Testing!
length Test
List length: 7
List length: 0
to_string Test
List is: r, i, n, g, i, n, g
List is: r-i-n-g-i-n-g
None # (THIS IS SUPPOSED TO DISPLAY: List is: )
测试代码:
import list_function
print("\nStart Testing!")
str_list1 = ['r', 'i', 'n', 'g', 'i', 'n', 'g']
str_list2 = ['r', 'e', 'd']
empty = []
print("\nlength Test")
print("List length:", list_function.length(str_list1))
print("List length:", list_function.length(empty))
print("\nto_string Test")
string = list_function.to_string(str_list1)
print(string)
string = list_function.to_string(str_list1, sep='-')
print(string)
print(list_function.to_string(empty))
print("\nEnd Testing!\n")
答案 0 :(得分:0)
我将作为评论更多地回答这个问题:
def to_string(my_list, sep=', '):
result = ' '
# only needed because of the odd return
msg = 'List is: '
# fine, but you only use it once, so why not put the literal there?
for char in my_list:
# why loop?
str_list1 = ['r', 'i', 'n', 'g', 'i', 'n', 'g']
# hard-coded the test...
if my_list == str_list1:
# ...so you guarantee it only works for one input - why?!
result = msg + sep.join(my_list)
# this line is useful
return result
# but only inside the for loop?!
你可以把这个功能简化为一行(你已经写了很多!),这样做的好处就是它会有任何意义并且有效。
这是一个与函数输出匹配的简化函数:
def to_string(my_list, sep=', '):
if my_list == ['r', 'i', 'n', 'g', 'i', 'n', 'g']: # test case
return 'List is: ' + sep.join(my_list)
elif len(my_list) > 0: # any other non-empty list
return ' '
else: # empty list
return None
这会让事情更清楚吗?这三种情况之间是否真的存在这么大的(或任何)差异?
答案 1 :(得分:0)
为什么不在elif
和else
部分写下其他条件?您已为一个条件编写,即仅在my_list == str_list1
时编写。但其他条件会发生什么?例如empty
列表?您可能也想检查一下。
def to_string(my_list, sep=', '):
result = ' '
msg = 'List is: '
str_list1 = ['r', 'i', 'n', 'g', 'i', 'n', 'g']
if my_list == str_list1:
result = msg + sep.join(my_list)
elif my_list == []: ## you can also use "len(my_list) == 0:"
result = msg
return result
现在您遇到问题None # (THIS IS SUPPOSED TO DISPLAY: List is: )
的原因是for
循环。for char in my_list:
仅在my_list
非空时运行。但是当你传递空列表时,for
循环将不会执行,因为它没有任何迭代。