【发布时间】:2018-03-25 00:10:18
【问题描述】:
我有一个代码,其中 return 语句似乎没有返回任何内容,但如果我在 return 语句正上方添加一个 print 语句,则 print 语句可以工作。例如:
return(test_list) #returns None
但如果我添加打印语句
print(test_list)
return(test_list) #print, prints the desired result
这怎么可能?
功能:
def reachable_destinations(iata_src: str, allowed: int, routes)\
-> List[Set[str]]:
"""The first parameters represents an IATA code. The second parameter is
the maximum number of direct flights allowed. The last parameter represents
route information. Return a list of the sets of IATA codes reachable from
the first parameter in steps from 0 up to (and including) the maximum
number of hops."""
#For example, with IATA code 'AA1', maximum number of flights as 2, and the following route information
#{'AA1': {'AA2', 'AA4'}, 'AA2': {'AA3'}, 'AA3': {'AA4', 'AA1'}, 'AA4': {'AA1'}}
#the result should be [{'AA1'}, {'AA2', 'AA4'}, {'AA3'}].
i = 0
reachable_list = [{iata_src}]
#print(reachable_list)
for i in range(allowed):
#print(i)
total_set = set()
#print(total_set)
for j in range(len(reachable_list[i])):
#print(j)
#print(routes[list(reachable_list[i])[j]])
total_set = total_set | routes[list(reachable_list[i])[j]]
#print(total_set)
dif = total_set - arbitrary_union(reachable_list)
#print(dif)
if dif == set():
print('dif is empty')
return reachable_list
else:
reachable_list.append(dif)
#print(reachable_list)
print(reachable_list)
return reachable_list
【问题讨论】:
-
“似乎没有任何回报”请提供minimal reproducible example
-
发布完整的函数,以及你如何调用函数
-
请发布函数以及调用它的位置。
-
so 如果最后一个打印语句未注释,该函数将打印所需的值,但如果我将其注释掉,则不会返回任何内容
-
切向但是:(1)不要做
dif == set()空集合是假的,所以你可以做if not dif(2)当你不需要时不要使用索引:total_set = set(routes[x] for x in reachable_list[i])