读取空间在python中分隔输入

gib*_*tar 15 python input

这是输入规范
程序必须读取t行输入.每行包含2个空格分隔值,第一个是名称,第二个是年龄.输入的一个例子

Mike 18
Kevin 35
Angel 56
Run Code Online (Sandbox Code Playgroud)

如何在python中阅读这种输入?如果我使用raw_input(),则在同一个变量中读取name和age.

更新 我将重新指出问题.我们已经知道如何在python中读取格式化输入.有没有办法可以在Python中读取格式化输入?如果是,那怎么样?

and*_*lme 27

the_string = raw_input()
name, age = the_string.split()
Run Code Online (Sandbox Code Playgroud)

  • 如果我必须读取数千或数百万的多个整数,并在输入时对它们进行操作,该怎么办? (3认同)
  • raw_input 在 python 3 中不再使用,你应该使用 list(map(str,input().split()))` (2认同)

Ros*_*ews 8

如果您将其包含在字符串中,则可以使用它.split()来分隔它们.

>>> for string in ('Mike 18', 'Kevin 35', 'Angel 56'):
...   l = string.split()
...   print repr(l[0]), repr(int(l[1]))
...
'Mike' 18
'Kevin' 35
'Angel' 56
>>>
Run Code Online (Sandbox Code Playgroud)


Mic*_*ael 5

假设您使用的是 Python 3,则可以使用此语法

inputs = list(map(str,input().split()))
Run Code Online (Sandbox Code Playgroud)

如果你想访问单个元素,你可以这样做

m, n = map(str,input().split())
Run Code Online (Sandbox Code Playgroud)