如何在 Python 3.8 中的一行中读取由空格分隔的多个输入? [英] How to read multiple inputs separated by space in a single line in Python 3.8?

查看:70
本文介绍了如何在 Python 3.8 中的一行中读取由空格分隔的多个输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试读取由空格分隔的 python 中的多个输入.它们都是整数、浮点数或双精度数.有没有办法在 python 3.8 中完成这项工作

I am trying to read multiple inputs in python separated by space. All of them are integers, float or double. Is there a way to get that done in python 3.8

推荐答案

你可以试试这个

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.

这篇关于如何在 Python 3.8 中的一行中读取由空格分隔的多个输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆