[英]Python input multiple lines and spaces
我試圖解決其中一個 a2oj 問題“給定三個數字 a、b 和 c。打印添加到自身的三個數字的總和。 ”
我帶着這個
import sys
numbers = [int(x) for x in sys.stdin.read().split()]
print(numbers[0] + numbers[1] + numbers[2])
我看到了很多主題,但我不知道如何從輸入中讀取 3 個值。 我知道我可以通過鍵入 CTRL+D 來停止這個過程,但是有沒有可能讓它自動(在達到第三個值之后)?
謝謝
// 感謝您非常快速的回答,我犯了錯誤,只發布了沒有輸入格式的問題陳述: “三個數字由一堆空格和/或新行分隔”
因此,例如輸入應如下所示:
2
1 4
// 好的,謝謝你們,我終於做到了:
n = []
while len(n) < 3:
s=input()
i = s.split()
[n.append(int(j)) for j in i]
print(2 * sum(n))
它正在工作,但是當我發送結果時,我得到了Runtime Error 。 我不知道為什么:鏈接: https://a2oj.com/p?ID=346
你可以只使用:
系統.argv
import sys
numbers = [int(x) for x in sys.argv[1:4]]
print(numbers)
print(sum(numbers))
在看到問題作者的更新並鏈接在線法官問題描述后,對其代碼所需的調整如下。 值得注意的是,預期的 output 是float
,精度設置為6
,而 output 是2 * sum of all inputs
,而不僅僅是sum
。 在線法官問題中沒有對此的描述,您必須從input
vs output
中了解。
n = []
while len(n) < 3:
s = input()
i = s.split()
n.extend(float(j) for j in i)
print(format(2 * sum(n), '.6f'))
下面的截圖
但是這個答案的第一個版本對於這個問題的第一個版本仍然有效。 如果其他人正在尋找以下情況,請保留它們。
通過enter
又名新行來分隔輸入:
numbers_List = []
for i in range(3):
number = int(input())
numbers_List.append(number)
print("Sum of all numbers: ", sum(numbers_List))
截屏:
按space
分隔輸入,也就是Bunch of spaces :
在輸入之前使用map
。 我建議也使用input
而不是sys.stdin.read()
來獲取用戶的輸入,用space
分隔,然后按Enter
鍵結束。
下面非常容易實現任意數量的輸入,並在列表中使用sum
function 添加:
numbers = list(map(int, input("Numbers: ").split()))
print("Sum of all numbers: ", sum(numbers))
下面的屏幕截圖和程序的鏈接在這里
閱讀 Python 的內置函數文檔以了解更多關於我上面使用的所有函數的信息。
我不確定您在尋找什么,但似乎您正在尋找的是來自 python 內置函數的輸入 function:
x=input()
這會將用戶的任何輸入作為字符串讀取。 然后,如果需要,您必須將其轉換為數字。
您可以讀取三個值:
numbers=[]
while (you have less than 3 numbers):
(input one line and add the numbers to your list)
(print the sum of your numbers)
由於您現在已經更准確地指定了問題陳述,我編輯了我的答案:
就您而言,這不是很復雜。 我不會馬上給你答案,因為它會破壞這一點,但我的想法是將輸入包裝在一個 while 循環中。 就像是:
numbers=[] while (you have less than 3 numbers): (input one line and add the numbers to your list) (print the sum of your numbers)
這樣,您就可以根據需要等待盡可能多的輸入,直到達到 3 個數字。 順便說一句,根據您的輸入,您可能需要檢查是否獲得的數字不超過 3 個。
from sys import stdin
sum = 0
for num in stdin.readline(4):
sum = sum + int(num)
print(sum)
from sys import argv
sum = 0
for num in argv[1:4]:
sum = sum + int(num)
print(sum)
根據您的用例使用 Python strip()
和split()
函數
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.