简体   繁体   中英

Store an input of multiple lines into a list in python

I have a simple question, I just want to store an input of multiple lines into an array using python, note that the first line of the input is telling me how many lines there will be, so if the first line of the input is 4, the whole input will be of 5 lines in total.

Example:

input:

4
1
2
3
4

output:

[1, 2, 3, 4]

I tried using n = list(map(int, input())) however when I print the whole list it only stores the first line of the input, and I need all the values.

Thank you.

Use a list comprehension, calling the input() function for each iteration, like so:

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

output for print(l) , with the first input being 4:

[1, 2, 3, 4]

This should work fine, looping in specific range and appending into a new list the inputs.

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

Output of print(new_list) , if the number_of_loop was 5:

[1, 1, 1, 1, 1]

Updated answer based on comment discussion.

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

print(li)

input

4
6
3
9
4

output

[ 6, 3, 9, 4 ]

I don't know if this solution is too basic

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

print(output)

If I input 4\n5\n6\n7\n2\n , I get the output:

[5, 6, 7, 2]

So, basically the first input gets the number of following inputs, and it is used to calculate the range of a for-loop , in which, for every iteration, an input and a list append is performed.

Please note how every input is returned in string format and needs to be converted into an integer.

input() reads whole single line. You can extend it using sys.stdin .

Now, In your case, each line contains a single integer so there can be two cases:

  • When you are given the number of integers to be read into the list: You can loop through multiple lines and read using int(input()) and append it to the list. (This is the your actual case):
#python 3.x
n = int(input())
ls = []
for i in range(n):
   ls.append(int(input())

or

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

if your input is like this

5
1
2
3
4
5

then value of n and ls will be

n = 5
ls = [1, 2, 3, 4, 5]
  • When you are not given the number of integers to be read into the list or don't know the size of list:
#python 3.x
import sys
ls = list(map(int, sys.stdin.read().strip().split())) #reading whole input from stdin then splitting

if your input is like this

1
2
3
4
5

then value of ls will be

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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