猿问

Python If/else 混淆

所以我的游戏有问题,我从这里复制粘贴了一部分。正如您所看到的,只有当列表位置的前 x 个元素小于 7 并且所有其余元素都大于 7 并且最后一个元素为 0 时,此代码才会打印 Yeah。但是,正如您在示例中看到的, 0 不是列表中的最后一个元素,但我得到了打印是的。为什么?谢谢你!


position=[3,6,4,2,5,0,10,12,7,8]

where=1

a=1

for i in range(6-where):

    if position[i]<7 and position[i]!=0:

        pass

    else:

        a=0

print(a)

for i in range(6-where,-1):

    if position[i]>6 and position[-1]==0:

        pass

    else:

        a=0

print(a)

print(position[-1])

if a==1:

    print("Yeah")


jeck猫
浏览 171回答 4
4回答

慕的地8271018

您可以选择将其放入函数中吗?如果是这样,尽早退出是你的朋友:def is_winner(nums, middle):&nbsp; &nbsp; # The last number must be a zero&nbsp; &nbsp; if nums[-1] != 0:&nbsp; &nbsp; &nbsp; &nbsp; return False&nbsp; &nbsp; # All of the starting numbers must be less than 7&nbsp; &nbsp; if not all(num < 7 for num in nums[:middle]):&nbsp; &nbsp; &nbsp; &nbsp; return False&nbsp; &nbsp; # All of the ending numbers must be at least 7&nbsp; &nbsp; if not all(num >= 7 for num in nums[middle:-1]):&nbsp; &nbsp; &nbsp; &nbsp; return False&nbsp; &nbsp; # If all of those are OK, then we've succeeded&nbsp; &nbsp; 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。如果不正确,请更新代码和示例以匹配。

温温酱

您的代码中可能有两个错误:第一个if语句中的行必须是 if position[i]<7 and position[-1]!=0:,但您已经编写了... and position[i]!=0其次,您的第二个 for 循环不会被执行,因为它的iterator 是range(6-where,-1), range 函数默认给出一个升序迭代器,所以在你的情况下迭代器是空的。对于降序列表,请向range func 添加一个step参数并使用。 这里最后一个-1是范围函数的步长range(6-where, -1, -1)

人到中年有点甜

你的代码看起来有点纠结。首先,使用布尔值和适当的名称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]]):&nbsp; &nbsp; &nbsp;if all([value > 6 for value in position[splitIndex:-1]]):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if position[-1] == 0:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;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):&nbsp; &nbsp; if position[i] >= 7 or position[i] == 0:&nbsp; &nbsp; &nbsp; &nbsp; valid_list = Falsefor i in range(len(position) - x - 1):&nbsp; &nbsp; if position[x + i] < 7 or position[i] == 0:&nbsp; &nbsp; &nbsp; &nbsp; valid_list = False&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;if valid_list and position[-1] == 0:&nbsp; &nbsp; print('Yeah')
随时随地看视频慕课网APP

相关分类

Python
我要回答