[英]Write a function that accepts a list of numbers and a single number as parameters. The function should print all the numbers less than the number
[英]Print all numbers less than the last number in a list in python
如何仅打印小于列表中最后一个数字的数字?
我正在尝试使用 python 打印列表中小于最后一个数字的所有数字。 该列表基于用户输入。 用户输入的示例数字是:
5
40
50
160
300
75
100 (the last number)
我不想打印第一个或最后一个数字。 第一个数字列出了列表中要检查的数字数量。 我的代码仅提供列表中的当前数字。 我不知道如何只获取小于列表中最后一个数字的数字。 我不想使用函数或数组。 这需要是 for/while/else/if/range 或 realm 中的内容。
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")
如果你有一个清单:
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]
def list_check(list):
big_number = list[-1]
for I in list[1:]:
if I < big_number:
print(I)
我不明白您希望用户输入如何参与其中,但是如果您通过它运行一个列表,它将检查最后一个数字与列表中不包括第一个数字的所有数字。
我可能倾向于对物品进行分类,因为当您可能碰到较大的物品时,您可以停止检查。 我可能会将列表排序为一个新列表并尝试检查效率。
此代码将打印更少的数字并添加到列表中
number1 = 100
number2 = 0
list1 = []
while True:
number2 += 1
list1.append(number2)
if number2 == number1:
list1.remove(number1)
break
print(list1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.