繁体   English   中英

返回数字大于列表中前一个数字的次数

[英]Return amount of times a number is greater than previous number in a list

我正在尝试从用户输入中检查列表并确定哪些数字大于前一个数字。 我可以用给定的列表和一个简单的 for 循环做到这一点

lst = [2, 4, 3, 5, 6, 5, 9]
count = 0

for n in range(1, len(lst)):   
    if lst[n] > lst[n-1]:
        count += 1
print(count)

但在指定用户输入时无法使其工作。 我正在尝试使用以 0 输入结束的 while 循环

lst = []
count = 0
finished = False

while not finished:
    n = int(input())
    if n != 0:
        lst.append(n)
        for i in range(0, len(lst)): 
            if lst[i] > lst[i-1]:
                count += 1
    else:
        finished = True
print(count)

for 循环独立工作并将输入附加到列表中,但我想知道为什么在将两者结合时代码没有返回正确的数字

代码中的错误在于每次给出新输入时整个列表lst都会完全迭代。

如果您首先使用 while 循环构建列表,然后计算在该列表中大于其前任的数字的数量,则应产生正确的结果。

lst = []
count = 0
finished = False

while not finished:
    n = int(input())
    if n != 0:
        lst.append(n)
        
    else:
        finished = True

for i in range(0, len(lst)): 
    if lst[i] > lst[i-1]:
        count += 1


print(count)

如果您不将输入存储在列表中,而是简单地存储最后一个输入并将其与新输入进行比较,您会更好。 然后你可以相应地增加你的计数器。

count = 0
finished = False
last = None
current = None

while not finished:
    n = int(input())
    if n != 0:
        last = current
        current = n
        
        if last != None and current > last:
            counter += 1
            
    else:
        finished = True

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM