首页 > 解决方案 > 打印所有小于python列表中最后一个数字的数字

问题描述

如何仅打印小于列表中最后一个数字的数字?

我正在尝试使用 python 打印小于列表中最后一个数字的所有数字。该列表基于用户输入。用户输入的示例数字是:

5
40
50
160
300
75
100 (the last number)

我不想打印第一个或最后一个数字。第一个数字列出了列表中要检查的数字数量。我的代码仅提供列表中的当前数字。我不知道如何只获取小于列表中最后一个数字的数字。我不想使用函数或数组。这需要 for/while/else/if/range 或该领域中的某些内容。

lst = [] #the list 
n = int(input()) #user input
  
for i in range(-1, n):
    ele = int(input())
    lst.append(ele) # adding the element'

print(*lst, sep = "\n")

标签: python

解决方案


如果你有一个清单:

List=[5, 40, 50, 160, 300, 75, 100]

List[-1]100

要打印小于100(列表中的最后一个元素)的所有元素:

n=int(input("Limit: "))) # Limiting number of comparisons with user input
smaller_numbers=[] # Creating a new list to store all the smaller values
for i in List[:n]: # Looping through the list to compare every element
    if i<List[-1]: # Seeing if the number is smaller than the last element of the list
        smaller_numbers.append(i) # if True the number will be appended to the new list

print(smaller_numbers)

输出:

(如果用户输入为 8):

[5, 40, 50, 75]

推荐阅读