Python中一次输入多行int数据的方法
笔试常用:
input_array = []
N = input()
for i in range(0, int(N)):
row = []
line = input()
temp_str = line.split(" ")
for str_ in temp_str:
row.append(int(str_))
input_array.append(row)
print(input_array)
输入:
3
1 2 3
4 5 6
7 8 9
输出:
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
### Python3:
#!/usr/bin/env python
# coding=utf-8
while True:
a=[]
s = input()
if s != "":
for x in s.split():
a.append(int(x))
# print(sum(a))
print(a)
else:
break
输入:
1 2
3 4
5 6
输出:
[1, 2]
[3, 4]
[5, 6]
a = []
while True:
s = input()
if s != "":
for x in s.split():
a.append(int(x))
# print(a)
else:
break
print(a)
输入:
1 2
3 4
5 6
输出:
[1, 2, 3, 4, 5, 6]
python中从控制台读入多行int型数据并保存每一行
from sys import stdin
team=[]
while True:
line = stdin.readline().strip() # strip()去掉最后的回车或者是空格
print(line)
if line=='':
break
item = line.split(' ')
print(item)
item = [int(i) for i in item]
team.append(item)
print(team)
输入:
1 2 3 4 # 数字中间有空格
5 6 7 8
输出:
1 2 3 4
['1', '2', '3', '4']
5 6 7 8
['5', '6', '7', '8']
[[1, 2, 3, 4], [5, 6, 7, 8]]
Python3使用input函数读取输入多行时回车不换行
stopword = '' # 输入停止符,遇到某一行为空停止
string = ''
for line in iter(input, stopword): # 输入为空行,表示输入结束
string += line + '\n'
print(string,type(string))
输入:
1 2 3 5
4 5 6 8 7
输出:
1 2 3 5
4 5 6 8 7
<class 'str'>
# 方法2
data = []
input_ch =''
while True:
input_ch = input()
if (input_ch == ':q'): # :q 为停止符
break
else:
data.append(input_ch)
#### 测试部分 ####
print(data)
with open('testfile_line.txt', 'w')as fw:
for item in data:
fw.writelines(item)
with open('testfile_line.txt', 'r')as fr:
read_data = fr.read()
print(read_data)
【下面做一道例题】:
题目描述:
大学的同学来自全国各地,对于远离家乡步入陌生大学校园的大一新生来说,碰到老乡是多么激动的一件事,于是大家都热衷于问身边的同学是否与自己同乡,来自新疆的小赛尤其热衷。但是大家都不告诉小赛他们来自哪里,只是说与谁是不是同乡,从所给的信息中,你能告诉小赛有多少人确定是她的同乡吗?
输入描述:
包含多组测试用例。
对于每组测试用例:
第一行包括2个整数,N(1 <= N <= 1000),M(0 <= M <= N*(N-1)/2),代表现有N个人(用1~N编号)和M组关系;
在接下来的M行里,每行包括3个整数,a,b, c,如果c为1,则代表a跟b是同乡;如果c为0,则代表a跟b不是同乡;
已知1表示小赛本人。
输入样例:
3 1
2 3 1
5 4
1 2 1
3 4 0
2 5 1
3 2 1
#!/usr/bin/env python
# coding=utf-8
import math
while True:
#每组第一行是N和M
nm = list(map(int,input().split(" ")))
N = nm[0]
M = nm[1]
print(str(N) + ' ' + str(M))
# 接下来M行,每行a b c
for i in range(M):
abc = list(map(int,input().split(" ")))
a = abc[0]
b = abc[1]
c = abc[2]
print(str(a) + ' ' + str(b) + ' ' + str(c))
#每组第一行是N和M
nm = list(map(int,input().split(" ")))
N = nm[0]
print(N)
arr = []
# 接下来M行,每行a b c
a = []
b = []
c = []
for i in range(N):
if i == N:
break
abc = list(map(int,input().split(" ")))
a1 = abc[0]
b1 = abc[1]
c1 = abc[2]
a.append(a1)
b.append(b1)
c.append(c1)
break
print(a,b,c)
输入:
3
1 2 3
4 5 6
7 8 9
输出:
[1, 4, 7] [2, 5, 8] [3, 6, 9]