英文:
What can I use instead of 'None' so it'll be iterable?
问题
"Is there something I can return instead of 'None' so that it's still iterable but empty?
Sometimes I want to return two values but sometimes I only want to return one.
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 #这里我想只返回'False'。
elif temp_cords in (white_locations + black_locations):
if white_turn:
if temp_cords in white_locations:
return True, (distance - 1) #但在这里,我想返回两个值。"
英文:
Is there something I can return instead of 'None' so that it's still iterable but empty?
Sometimes I want to return two values but sometimes I only want to return one.
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.
答案1
得分: 0
不建议设计一个返回长度根据不同条件变化的元组的函数,因为调用者无法将返回的元组简单地解包成固定数量的变量。
在您的情况下,最好不返回布尔值,而是默认情况下只返回distance - 1
,然后可以选择:
- 当
temp_cords in all_locations
为True
时,返回None
,以便调用者可以检查返回值是否为None
来决定如何处理返回值 - 或者引发异常,以便调用者可以在
try-except
块中调用该函数来处理temp_cords in all_locations
为True
的情况。
英文:
It is never a good design to create a function that returns a tuple whose length can vary based on different conditions because the caller would not be able to simply unpack the returning tuple into a fixed number of variables.
In your case, it is better to not return a Boolean but simply return distance - 1
by default, and then either:
return None
whentemp_cords in all_locations
isTrue
, so that caller can just check whether if the returning value isNone
to decide what to do with the returning value- or, raise an exception so that the caller can call the function in a
try-except
block to handle the condition whentemp_cords in all_locations
isTrue
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论