多行输入输出问题 Python3 模板样例【牛客网】

写在前面

好多人推荐用牛客网进行刷题,发现牛客网和我之前高中的时候AC题目的输入,输出格式竟然有几分相似的呢,都是可能提交了通过0个,嘤嘤嘤,今天整理一下避免以后面试的时候踩坑。

一.单行输入

题目形式比如:
input 每次字符串形式读一行的数据,

a = input().split()
a1 = []
for k in a:
    # a1.append(k)#str
    a1.append(int(k))#int,得到list,推荐用下面那个一句话的

或者

line = list(map(int,input().split(' '))) #直接得到list

只是输入一个数字的情况

n = int(input())#输入只是一个数字

二.多行输入

(一) 首行只有一个数字n

1.行数n已知

'多行输入'
res = []
n = int(input())#行数
for _ in range(n):
    s = input()
    if s!='':
        temp = [j for j in s.split()] #str输入
        # temp = [int(j) for j in s.split()] #int输入
        res.append(temp[0])
    else:
        break
print(res)

注:注意输出要求的差异

①. 每行输出一个(默认)

def F(data):
    return data
 
'多行输入'
res = []
n = int(input())#行数
for _ in range(n):
    s = input()
    if s!='':
        temp = [j for j in s.split()] #str输入
        # temp = [int(j) for j in s.split()] #int输入
        res.append(temp[0])
    else:
        break
 
for i in res:
    print(F(i)) #每行只输出一个
    # print(F(i), end=' ') #全在同一行内输出,用空格隔开

②全在同一行输出,用空格隔开

'多行输入'
res = []
n = int(input())#行数
for _ in range(n):
    s = input()
    if s!='':
        temp = [j for j in s.split()] #str输入
        # temp = [int(j) for j in s.split()] #int输入
        res.append(temp[0])
    else:
        break
 
for i in res:
    # print(F(i)) #每行只输出一个
    print(i, end=' ') #全在同一行内输出,用空格隔开

2.行数n未知

'多行输入,行数未知'
res = []
while True:
    try:
        s = input()
        # res.append(list(map(int, s.split(' '))))
        res.append(list(map(str, s.split(' '))))
    except:
        break

首行有2个数字n,m ——> 往下n行数据对应n, 再m行数据对应m

info = list(map(int,input().split(' ')))
a = []
b = []
for i in range(info[0]):
    a.append(input().split(' '))
for j in range(info[1]):
    b.append(input().split(' '))
print(a)
print(b)

在这里插入图片描述

发布了157 篇原创文章 · 获赞 94 · 访问量 11万+

猜你喜欢

转载自blog.csdn.net/weixin_42462804/article/details/105133131