在Python中,输入多行数据可以通过以下几种方法实现:
1. 使用`input()`函数结合循环:
n = int(input("请输入行数:"))
lst = []
for i in range(n):
s = input(f"请输入第{i+1}行:")
lst.append(s)
print(lst)
2. 使用`while`循环:
s = ""
while True:
line = input("请输入一行文本(或按Enter结束):")
if not line:
break
s += line + "\n"
print(s.strip())
3. 使用`for`循环结合`sys.stdin`:
import sys
strList = []
for line in sys.stdin:
strList.append(line.strip())
print(strList)
4. 使用`try-except`结构处理输入结束信号:
lines = []
while True:
try:
lines.append(input())
except EOFError:
break
print(lines)
5. 使用`with open`读取文本文件中的所有行:
with open('data.txt', 'r') as file:
lines = file.readlines()
print(lines)
以上方法都可以实现多行数据的输入,具体使用哪种方法取决于你的使用场景和需求