我可以使用什么来代替“无”,这样它就可以迭代了? [关闭]

问题描述 投票:0回答:1

有什么我可以返回而不是“无”的东西,这样它仍然可以迭代但为空吗? 有时我想返回两个值,但有时我只想返回一个值。

for distance in range(1, 8):

    temp_cords = [(origin[0] - ((origin[0]-check[0])*distance)), (origin[1] - ((origin[1]-check[1])*distance))]

    if temp_cords in all_locations:
        return False, None #I want to return only 'False' here.

    elif temp_cords in (white_locations + black_locations):

        if white_turn:

            if temp_cords in white_locations:
                return True, (distance - 1) #But here, I want to return two values.
python return-type nonetype iterable-unpacking
1个回答
0
投票

创建一个返回长度会根据不同条件变化的元组的函数从来都不是一个好的设计,因为调用者无法简单地将返回的元组解压缩到固定数量的变量中。

在您的情况下,最好不要返回布尔值,而是默认返回

return distance - 1
,然后:

  • return None
    temp_cords in all_locations
    True
    时,调用者只需检查返回值是否为
    None
    来决定如何处理返回值
  • 或者,引发异常,以便调用者可以调用
    try-except
    块中的函数来处理
    temp_cords in all_locations
    True
    时的条件。
© www.soinside.com 2019 - 2024. All rights reserved.