python - Python If/else 混淆
问题描述
所以我的游戏有问题,我在这里复制粘贴了一部分。如您所见,仅当列表位置的前 x 个元素小于 7 并且所有其余元素均大于 7 且最终元素为 0 时,此代码才会打印 Yes。但是,正如您在示例中看到的那样, 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")
解决方案
您的代码中可能有两个错误:
首先是 https://stackoverflow.com/users/10788239/arkleseisure
第一个if语句中的行必须是
if position[i]<7 and position[-1]!=0:
,但是您已经编写
... and position[i]!=0
了第二个 for 循环没有被执行,因为它iterator is range(6-where,-1)
, range 函数默认给出一个升序迭代器,所以在你的情况下迭代器是空的。对于降序列表,将step参数添加到range func 并使用range(6-where, -1, -1)
。
这里最后一个-1是范围函数的步长
推荐阅读
- spring - RestTemplate - Spring 4 到 Spring 5 升级中的行为变化
- laravel - 如何在 Laravel Cashier 更新卡后立即尝试收费?
- java - 为什么HDFS FileNotFoundException:文件不存在?
- java - 模拟访问内部创建的对象验证
- python - 如何在 Selenium Python 中获得类似人类的鼠标点击?
- r - 闪亮的小部件小于应用程序宽度,我如何使两边的填充不是白色的?
- html - 内容未在移动视图的页面上向下推页脚
- c# - 如何在一种方法中为数组赋值并从另一种方法调用
- node.js - 打字稿阻止出口在全球范围内可用?
- python - 在 python (pandas.DataFrame) 中,是否有一种简单/有效的方法来创建每个索引中一列的所有可能组合,按值评分?