簡體   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