【发布时间】:2021-08-29 21:08:47
【问题描述】:
我对 Python 很陌生,所以提前抱歉,如果随机数不在数字列表中,我会尝试跳出 While 循环。 尽管测试了函数的输出并确认一个整数在列表中并且它实际上是一个整数,并且其他方法同时返回 True 和 False,但 While 语句会忽略该值。查看演示代码。
import random,time
list=[i for i in range(10)]
print(list)
print(list[6]*10) # this returns an integer
if list[6]==12/2:
print('this evaluates as a int')
this=99 # sentry to run the while loop **** but cant index by
if 10/2 in list:
print('this also evaluates as an integer')
print(type(list))
print(type(this))
while this not in list:
this = random.randrange(9)
print(this,this in list)
time.sleep(.200)
list[this] = '*'
>>>
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
60
this evaluates as a int
this also evaluates as an integer
<class 'list'>
<class 'int'>
6 True
3 True
4 True
5 对
5 False
【问题讨论】:
-
您在打印之前重新分配
this。因此,您会看到与最后一次在 while 循环中求值的值不同的值。 -
此外,使用
list[this] = '*'将位置this上的元素设置为*。所以这些项目将被替换为*并且this not in list不能是True。 -
你应该更好地解释你真正想要做什么来帮助你。整个程序对我来说真的没有意义。
-
我希望 While 循环遍历循环,而 List 中存在整数 0 到 9,我使用“*”删除该整数一旦使用。当列表中没有整数时,我想跳出循环
标签: python-3.x while-loop