Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何使循环运行到它不再有意义的时候?_Python_Python 3.x_Loops_While Loop - Fatal编程技术网

Python 如何使循环运行到它不再有意义的时候?

Python 如何使循环运行到它不再有意义的时候?,python,python-3.x,loops,while-loop,Python,Python 3.x,Loops,While Loop,我在程序中有一个循环,应该是 while number >= lst[count]: rank -= 1 count += 1 我想让它一直运行,直到它不再有意义。我尝试了一些不起作用的事情(见文章末尾),但以下几点起了作用: lst = [int(x) for x in input().split()] number = int(input()) count = 0 rank = 0 def attempt(lst, a): try: resu

我在程序中有一个循环,应该是

while number >= lst[count]:
    rank -= 1
    count += 1
我想让它一直运行,直到它不再有意义。我尝试了一些不起作用的事情(见文章末尾),但以下几点起了作用:

lst = [int(x) for x in input().split()]
number = int(input())
count = 0
rank = 0

def attempt(lst, a):
    try:
        result = lst[a]
    except:
        result = float('inf')
    return result


while number >= attempt(lst, count):
    rank -= 1
    count += 1
print(rank)
然而,我不认为这是非常优雅,似乎做作。是否有更优雅的解决方案(对于这种情况,通常对于给定条件)


其他尝试(未成功):

而aliceScores[i]>=lst[count]和count
上述操作失败,因为while尝试运行count=len(lst)并运行错误,因为lst[len(lst)]不存在

while aliceScores[i] >= lst[count] and count < len(lst)-1:
    rank -= 1
    count += 1
而aliceScores[i]>=lst[count]和count
上述操作失败,因为如果在lst[len(lst)-1]的情况下也发生这种情况,我想修改秩,这在上述代码中似乎不存在。

唯一的原因是

while aliceScores[i] >= lst[count] and count < len(lst):
    rank -= 1
    count += 1
而aliceScores[i]>=lst[count]和count
当count太大时,不能计算lst[count],但可以利用python这一事实

而count=lst[count]:
排名-=1
计数+=1

这样,如果计数太大,或者第二个条件变为False,循环将正确停止。

为什么不使用
for
来迭代列表,使用
枚举来计算尝试次数呢。
它将比
while
imho更像蟒蛇

def get_rank(...):
   for index, lst_number in enumerate(lst):
       if number < lst_attempt:
           return -index
   return -len(lst)
def get_rank(…):
对于索引,枚举中的lst_编号(lst):
如果编号
完美!非常感谢。有点奇怪的是,“and”不是有效的交换性。布尔运算符短路几乎是通用的约定,这比交换性有用得多。
while count < len(lst) and aliceScores[i] >= lst[count]:
    rank -= 1
    count += 1
def get_rank(...):
   for index, lst_number in enumerate(lst):
       if number < lst_attempt:
           return -index
   return -len(lst)