且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 Python 3.8 中的一行中读取由空格分隔的多个输入?

更新时间:2023-11-22 14:42:34

你可以试试这个

var = input.split(" ")

以上代码将创建一个字符串数组.

Above code will create an array of string.

例如给定输入 1 2 3 4 5 ,它将创建一个包含元素 ["1", "2", "3", "4", "5" 的 var 数组]

for eg given input 1 2 3 4 5 , it'll create an array of var with elements ["1", "2", "3", "4", "5"]

请注意,上面的代码将每个元素存储为一个字符串.如果你想改变元素的数据类型,你可以使用 map 函数.

Note that the above code will store each element as a string. If you want to change the data type of the elements you can use map function.

var_integers = list(map(int, input.split()))

这将创建一个整数数组.以上面的 1 2 3 4 5 为例,它将创建一个数组 var_integers,其元素为 [1, 2, 3, 4, 5]

This'll create an array of integer. Taking above example of 1 2 3 4 5, it'll create an array var_integers with elements [1, 2, 3, 4, 5]

您可以使用任何函数代替 ma​​p 函数中的 int 来转换可迭代对象(此处 input().split() 创建了一个字符串元素列表,如所述)上面作为一个可迭代对象)作为第二个参数传递.

You can use any function in place of int in map function to transform the iterable (here input().split() creates a list of string elements as stated above which acts as an iterable) passed as a second argument.

例如,如果您使用 float 而不是 int,那么输入字符串将被转换为 float 然后存储在数组中.

For example if you use float instead of int then the input string will be converted to float then stored in array.

您也可以通过以下方式将元素直接存储到变量中,而不是存储在数组中:

You can also store the elements directly into variable instead of storing in an array by:

var1, var2, var3 .. ,varn = map(int, input().split())

在这里,您必须指定确切的变量数作为输入字符串中由空格分隔的元素数.

Here you have to specify exact number of variables as the number of elements separated by space in the input string.