python - 打印所有小于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")
解决方案
如果你有一个清单:
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]
推荐阅读
- matlab - Matlab 创建新的 Microsoft Access 数据库文件 *.accdb
- java - JSON - 无法使用 Jackson 和 JPA 序列化 Object 中的 JSONObject
- apache-spark - 将 Spark 2.3.0 数据集保存为图像格式
- python - 如何在python中返回re.search()的字符串表示
- swift - Swift - 使用搜索栏后出现结果错误
- java - 由 keycloak 的 java 适配器创建的连接上的“keep-alive”标头
- c - Xv6中P2V、V2P宏背后的机制是什么
- java - Hive JDBC 连接设置或与 MySQL 的映射
- go - golang 的手册页?
- javascript - 如何确定用户是否在 Javascript 中附加了键盘