Python中不同行的输入和输出

发布于 2025-01-14 01:17:30 字数 347 浏览 2 评论 0原文

我目前正在尝试解决最大值问题。 然而,我现在很难同时获得许多输出。 我尝试使用 input().splitlines() 来执行此操作,但我只得到一个输出。测试用例和输出需要有很多行,就像盒子的示例一样。如果有人能为我提供一些帮助,我将不胜感激。

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) 

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. 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) 

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

北风几吹夏 2025-01-21 01:17:31

input 不处理多行,您需要循环。您可以将 iter 与哨兵一起使用来重复输入并打破循环(此处为空行)。

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

示例:

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

[3, 6, 9]

注意。此代码没有任何检查,仅当您输入以逗号分隔的整数时才有效

input does not handle multiline, you need to loop. You can use iter with a sentinel to repeat the input and break the loop (here empty line).

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

倒带 2025-01-21 01:17:31

你能试试这个吗?

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)

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)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文