输入:
359716482
867345912
413928675
398574126
546281739
172639548
984163257
621857394
735492861
我的代码:
print("Enter the array:\n")
userInput = input().splitlines()
print(userInput)
我的问题是,userInput
只接受第一行的值,但它似乎没有接受第一行之后的值?
输入:
359716482
867345912
413928675
398574126
546281739
172639548
984163257
621857394
735492861
我的代码:
print("Enter the array:\n")
userInput = input().splitlines()
print(userInput)
我的问题是,userInput
只接受第一行的值,但它似乎没有接受第一行之后的值?
您可以使用readlines()
文件对象的方法:
import sys
userInput = sys.stdin.readlines()
您可以使用生成器轻松创建一个。这是一种这样的实现。请注意,您可以按空白返回或任何键盘中断来跳出输入循环
>>> def multi_input():
try:
while True:
data=raw_input()
if not data: break
yield data
except KeyboardInterrupt:
return
>>> userInput = list(multi_input())
359716482
867345912
413928675
398574126
>>> userInput
['359716482', '867345912', '413928675', '398574126']
>>>
每个input()
只接受一行。围绕这一点的策略:
input()
,直到它收到一个空行input()
,直到用户在类似 UNIX 的操作系统上执行 ctrl-D,此时将引发 EOFError,您可以捕获它您也可以尝试使用 python 文件处理:
userInput = []
with open("example.txt", "r") as f :
for x in f :
userInput.append(x)
但是,在这种情况下,您需要将输入作为文本文件 (example.txt) 提供。
你好呀,
你可以试试我根据你的要求做的这个方法。我在代码上添加了一些注释来解释我想要实现的目标。很高兴有机会学习一些 python 代码,我是这种语言的新手,但我非常喜欢它!
def multi_input():
try:
#This list will hold all inputs made during the loop
lst_words = []
# We will store the final string results on this variable
final_str =''
#Let's ask first the user to enter the amount of fruits
print("Please Type in your List of Fruits. \n Press << Enter >> to finish the list:")
#Loop to get as many words as needed in that list
while True:
#Capture each word o'er here, pals!
wrd = input()
# If word is empty, meaning user hit ENTER, let's break this routine
if not wrd: break
# if not, we keep adding this input to the current list of fruits
else:
lst_words.append(wrd)
#What if ther user press the interruption shortcut? ctrl+D or Linus or MacOS equivalent?
except KeyboardInterrupt:
print("program was manually terminated by the user.")
return
#the time has come for us to display the results on the screen
finally:
#If the list has at least one element, let us print it on the screen
if(len(lst_words)>0):
#Before printing this list, let's create the final string based on the elements of the list
final_str = '\n'.join(lst_words)
print('You entered the below fruits:')
print(final_str)
else:
quit
#let us test this function now! Happy python coding, folks!
multi_input()
lines = []
while True:
s =input("Enter the string or press ENTER for Output: ")
if s:
lines.append(s)
else:
break;
print("OUTPUT: ")
for i in lines:
print (i)
Input:
359716482
867345912
413928675
398574126
546281739
172639548
984163257
621857394
735492861
Output:
359716482
867345912
413928675
398574126
546281739
172639548
984163257
621857394
735492861