慕的地8271018
您可以选择将其放入函数中吗?如果是这样,尽早退出是你的朋友:def is_winner(nums, middle): # The last number must be a zero if nums[-1] != 0: return False # All of the starting numbers must be less than 7 if not all(num < 7 for num in nums[:middle]): return False # All of the ending numbers must be at least 7 if not all(num >= 7 for num in nums[middle:-1]): return False # If all of those are OK, then we've succeeded return True# This will print False because it doesn't end in 0.position = [3, 6, 4, 2, 5, 0, 10, 12, 7, 8]print(is_winner(position, 6))# This will print True because it meets the requirements.position = [3, 6, 4, 2, 5, 0, 10, 12, 7, 8, 0]print(is_winner(position, 6))# This will print False because a number in the first part is greater than 7position = [3, 6, 4, 2, 5, 0, 10, 12, 7, 8, 0]print(is_winner(position, 7))# This will print False because a number in the second part is not at least 7position = [3, 6, 4, 2, 5, 0, 10, 12, 7, 8, 0]print(is_winner(position, 5))看看这个函数如何变得非常简单和可读?在每一步中,如果不满足要求,您就会停止。您不必跟踪状态或任何东西;你只需返回 False 即可。如果您到达函数末尾并且没有失败任何测试,那么 ta-da!您成功了并且可以返回 True。顺便说一句,根据你的例子,第二个要求应该是x >= 7,而不是x > 7。如果不正确,请更新代码和示例以匹配。
人到中年有点甜
你的代码看起来有点纠结。首先,使用布尔值和适当的名称a。例如listValid = True。但没有它也是可能的。position=[3,6,4,2,5,0,10,12,7,8]splitIndex = 6 - 1if all([value < 7 for value in position[:splitIndex]]): if all([value > 6 for value in position[splitIndex:-1]]): if position[-1] == 0: print("Yeah")
慕容708150
在第一个 if 语句中,您有位置 [i] 而不是位置 [-1]。这里还有一些改进的、更简单的代码:position=[3,6,4,2,5,0,10,12,7,8]x = 5valid_list = Truefor i in range(x): if position[i] >= 7 or position[i] == 0: valid_list = Falsefor i in range(len(position) - x - 1): if position[x + i] < 7 or position[i] == 0: valid_list = False if valid_list and position[-1] == 0: print('Yeah')