[英]How to read all inputs from STDIN in Hackerrank?
我已經學習了 Python 的一些基礎知識,並想在 Hackerrank 中嘗試簡單的挑戰。
輸入格式:第一行包含 integer,第二行包含空格分隔的整數列表,第三行包含另一個 integer。
在編碼部分,它說# Enter your code here. Read input from STDIN. Print output to STDOUT
# Enter your code here. Read input from STDIN. Print output to STDOUT
我在閱讀和保存 STDIN 時遇到困難。 我想將第一行 integer 保存為X
,第二行列表保存為list
,第三行 integer 保存為N
。
我不明白該怎么做。 我用谷歌搜索並嘗試使用一些現有的代碼,但不斷出錯。
您可以使用input
:
# the first line contains integer
integer1 = int(input())
# the second line contains the space separated list of integers
int_lst = list(map(int, input().split()))
# third line contains another integer.
integer2 = int(input())
lst = [list(map(int, input().split())) for _ in range(10)]
我們可以使用 input() 從 STDIN 接收輸入並將其轉換為 int 作為 input() function 將 STDIN 作為字符串返回。
要接收 integer:
>>> x = int(input().strip())
12
>>> x
12
要將空格分隔的整數列表轉換為列表:
>>> y = list(map(int,input().strip().split(' ')))
1 2 3 4 556
>>> y
[1, 2, 3, 4, 556]
創建二維整數列表:
>>> rows = 3
>>> array = []
>>> for i in range(rows):
... each_line = list(map(int,input().strip().split(' ')))
... array.append(each_line)
...
1 2 3
4 5 6
7 8 9
>>> array
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.