【问题标题】:Return amount of times a number is greater than previous number in a list返回一个数字大于列表中前一个数字的次数
【发布时间】:2021-10-13 20:26:48
【问题描述】:

我正在尝试检查来自用户输入的列表并确定哪些数字大于前一个数字。我可以用给定的列表和一个简单的 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 循环自行工作并将输入附加到列表中工作,但我想知道为什么将两者结合起来时代码不会返回正确的数字

【问题讨论】:

  • 如果你只是比较最后一个输入,你真的不需要列表吗?
  • 检查你的第二个sn-p上的range比较第一个,你可能会发现问题。
  • @Chris 很好,他应该只需要存储以前的数字,如果当前输入更大,则增加他的计数器。应该对运行时有很大帮助。
  • 更不用说,每次迭代当前代码中的列表时,您都不会重置计数器。如果我有 [1,2,3],那count 是 2,但如果下一个输入是 4,那么你的代码会变为“[1,2,3,4] - 让我将计数器增加 3 倍!”所以最终计数是 5,而不是 3。

标签: python while-loop


【解决方案1】:

代码中的错误在于,每次给出新输入时,整个列表 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多