简体   繁体   English

Python中输入和output的不同行

[英]Different lines of input and output in Python

I'm currently trying to solve the max value problem.我目前正在尝试解决最大值问题。 However, I'm now having a hard time getting many outputs at the same time.但是,我现在很难同时获得许多输出。 I try to use input().splitlines() to do it, but I only get one output. The test case and output need to have many lines just as the box's examples.我尝试使用 input().splitlines() 来做到这一点,但我只得到一个 output。测试用例和 output 需要有很多行,就像盒子的例子一样。 If anyone can provide me with some assistance, I would be very much appreciated it.如果有人可以为我提供一些帮助,我将不胜感激。

Example:
Input:
1,2,3
4,5,6
7,8,9

output:
3 
6
9

for line in input().splitlines():

   nums = []
   for num in line.split(','):
       nums.append(int(num))
       print(nums)
   max(nums) 

input does not handle multiline, you need to loop. input不处理多行,你需要循环。 You can use iter with a sentinel to repeat the input and break the loop (here empty line).您可以将iter与哨兵一起使用来重复输入并打破循环(此处为空行)。

nums = []
for line in iter(input, ''):
    nums.append(max(map(int, line.split(','))))
print(nums)

example:例子:

1,2,3
4,5,6
7,8,9

[3, 6, 9]

NB.注意。 this code does not have any check and works only if you input integers separated by commas此代码没有任何检查,仅当您输入以逗号分隔的整数时才有效

Can you try this out?你能试试这个吗?

max_list = []

while True: #loop thru till you get input as input() reads a line only
    line_input = input() #read a line
    if line_input: #read till you get input.
        num_list = []
        for num in line_input.split(","):  #split the inputs by separator ','
            num_list.append(int(num))  # convert to int and then store, as input is read as string
        max_list.append(max(num_list))
    else:
        break #break when no input available or just 'Enter Key'

for max in max_list:
    print(max)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM