首页 > 解决方案 > 如何在 Python 中获取多行输入(用于编程问题)?

问题描述

在编程问题中,我收到如下输入:

6
7
8
5
4

在这种情况下,我想创建一个类似 [6, 7, 8, 5, 4] 的列表,即输入中的数字列表。

我尝试直接从输入中读取,但后来我打印了我的列表,发现它是 [6],所以它只读取第一行。

lst = []
    while True:
        n = input()
        if n != '':
            lst.append(int(n))
        else: 
            break
    print(lst)

这给了我一个EOF错误。

标签: python-3.x

解决方案


使用try-except

lst = []
while True:
    try:
        n = input()
        lst.append(int(n))
    except EOFError:
        break
print(lst)

推荐阅读