[英]Accepting input till newline in python
我是python初學者。 只要他/她願意,我就會嘗試接受用戶的輸入。 當單獨按下回車鍵時,程序應該停止接受輸入。
那就是
25
65
69
32
#stop here since the enter key was pressed without any input
我想出了以下代碼來做到這一點....
a = []
while 1:
b = input("->")
if(len(b)>0):
a.append(b)
else:
break
有沒有其他有效的“pythonic”方法可以做到這一點?
雖然這與 python 3.3 完美兼容,但它不適用於 python 2.7(用 raw_input() 函數替換 input() )。 屏幕只是保持沉默,沒有任何反應。 為什么?
是否有任何內置函數可以將字符串轉換回整數!?
你的方法基本沒問題。 你可以這樣寫:
a = []
prompt = "-> "
line = input(prompt)
while line:
a.append(int(line))
line = input(prompt)
print(a)
注意:我沒有包含任何錯誤處理。
至於你的其他問題:
raw_input()
應該在 Python 2.7 中類似地工作int()
-- 將給定的參數轉換為整數。 如果不能,它將失敗並顯示TypeError
。 對於 Python 2.x 版本,只需將input()
換成raw_input()
。
僅出於教育目的,您也可以像這樣以函數式風格編寫它:
def read_input(prompt):
x = input(prompt)
while x:
yield x
x = input(prompt)
xs = list(map(int, read_input("-> ")))
print(xs)
可能是我所知道的最巧妙的方法(不幸的是,沒有錯誤處理,這就是為什么您在生產中不會經常看到它):
>>> lines = list(iter(input, ''))
abc
def
.
g
>>> lines
['abc', 'def', '.', 'g']
這對iter
使用雙參數調用簽名,它調用第一個參數 ( input
) 直到它返回第二個參數(此處為''
,空字符串)。
你的方式還不錯,雖然它在變體下更常見
a = []
while True:
b = input("->")
if not b:
break
a.append(b)
實際上,使用break
和continue
是許多人執行單行if
的罕見情況之一,例如
a = []
while True:
b = input("->")
if not b: break
a.append(b)
雖然這是正式皺眉(tm)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.