减少 return 语句的数量 (Python)
Reducing the amount of return statements (Python)
下面的函数 return 是列表 list_of_items 中等于 search_item 的第一项的索引。如果不存在这样的项目,则函数 returns -1.
使用 while 循环而不是 for 循环,并且不使用任何 break 语句或列表的索引方法。如何减少下面的函数,使其只包含一个 return 语句?
由于 while
循环的限制,并且不使用任何 break
语句(使这看起来很像家庭作业问题),最好的办法是创建第二个条件来控制循环的执行。例如:
def my_index(list_of_items, search_item):
i = 0
done = False
return_value = '-1' # I suspect you meant this to be an int, not str
while i < len(list_of_items) and not done:
if list_of_items[i] == search_item:
done = True
return_value = i
else:
i += 1
return return_value
这算是破解吗?
def my_index(list_of_items, search_item):
res = -1
i = 0
while i < len(list_of_items):
if list_of_items[i] == search_item:
res = i
i = len(list_of_items)
else:
i += 1
return res
def my_index(list_of_items, search_item):
ret = -2
i = 0
while i < len(list_of_items):
if list_of_items[i] == search_item:
ret = i
elif i == (len(list_of_items) - 1):
ret = -1
if ret != -2:
return ret
i += 1
list_of_items = [3, 7, 2, 9, 11, 19]
print(my_index(list_of_items, 3))
下面的函数 return 是列表 list_of_items 中等于 search_item 的第一项的索引。如果不存在这样的项目,则函数 returns -1.
使用 while 循环而不是 for 循环,并且不使用任何 break 语句或列表的索引方法。如何减少下面的函数,使其只包含一个 return 语句?
由于 while
循环的限制,并且不使用任何 break
语句(使这看起来很像家庭作业问题),最好的办法是创建第二个条件来控制循环的执行。例如:
def my_index(list_of_items, search_item):
i = 0
done = False
return_value = '-1' # I suspect you meant this to be an int, not str
while i < len(list_of_items) and not done:
if list_of_items[i] == search_item:
done = True
return_value = i
else:
i += 1
return return_value
这算是破解吗?
def my_index(list_of_items, search_item):
res = -1
i = 0
while i < len(list_of_items):
if list_of_items[i] == search_item:
res = i
i = len(list_of_items)
else:
i += 1
return res
def my_index(list_of_items, search_item):
ret = -2
i = 0
while i < len(list_of_items):
if list_of_items[i] == search_item:
ret = i
elif i == (len(list_of_items) - 1):
ret = -1
if ret != -2:
return ret
i += 1
list_of_items = [3, 7, 2, 9, 11, 19]
print(my_index(list_of_items, 3))