繁体   English   中英

将多行的输入存储到 python 中的列表中

[英]Store an input of multiple lines into a list in python

我有一个简单的问题,我只想使用 python 将多行的输入存储到一个数组中,注意输入的第一行告诉我会有多少行,所以如果输入的第一行是 4 ,整个输入总共将是 5 行。

例子:

输入:

4
1
2
3
4

output:

[1, 2, 3, 4]

我尝试使用n = list(map(int, input()))但是当我打印整个列表时,它只存储输入的第一行,并且我需要所有值。

谢谢你。

使用列表推导,为每次迭代调用input() function,如下所示:

l = [int(input()) for _ in range(int(input()))]

output 用于print(l) ,第一个输入为 4:

[1, 2, 3, 4]

这应该可以正常工作,在特定范围内循环并将输入附加到新列表中。

new_list = []
number_of_loop = int(input())
for _ in range(number_of_loop):
    new_list.append(int(input()))

Output 的print(new_list) ,如果number_of_loop为 5:

[1, 1, 1, 1, 1]

根据评论讨论更新答案。

num = input()
li = []
for _ in range(num):
    data = int(input())
    li.append(data)

print(li)

输入

4
6
3
9
4

output

[ 6, 3, 9, 4 ]

我不知道这个解决方案是否太基础

output = []
tot = int(input())
for i in range(tot):
    num=int(input())
    output.append(num)

print(output)

如果我输入4\n5\n6\n7\n2\n ,我会得到 output:

[5, 6, 7, 2]

因此,基本上第一个input获取后续输入的数量,并用于计算for-loop的范围,其中,对于每次迭代,都会执行一个input和一个列表append

请注意每个input如何以字符串格式返回,并且需要转换为 integer。

input()读取整行。 您可以使用sys.stdin对其进行扩展。

现在,在您的情况下,每一行都包含一个 integer 所以可能有两种情况:

  • 当您获得要读入列表的整数数量时:您可以遍历多行并使用int(input())和 append 将其读取到列表中。 (这是您的实际情况):
#python 3.x
n = int(input())
ls = []
for i in range(n):
   ls.append(int(input())

或者

#python 3.x
import sys
n = int(input())
ls = list(map(int,sys.stdin.read().strip().split()))

如果你的输入是这样的

5
1
2
3
4
5

那么nls的值将是

n = 5
ls = [1, 2, 3, 4, 5]
  • 当您没有获得要读入列表的整数数量或不知道列表的大小时:
#python 3.x
import sys
ls = list(map(int, sys.stdin.read().strip().split())) #reading whole input from stdin then splitting

如果你的输入是这样的

1
2
3
4
5

那么ls的值将是

ls = [1, 2, 3, 4, 5]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM