如何在python中动态地读取用空格分隔的输入,最好是在List上读取不同类型的数据?

问题描述 投票:-3回答:4

有没有一种方法可以插入 第一 输入为 接下来 输入为 接下来 作为 浮动 到一个列表中。假设三个输入之间用空格隔开,就会被当作输入,那么有没有办法把第一个输入插入为str,下一个输入插入为int,下一个输入插入为float,插入到一个列表中。

data = map(str,int,float,input.split()) # Something like this, I know the syntax here is wrong
python python-3.x list input
4个回答
1
投票

你可以用简单的方法。

task = input().split()
task[1] = int(task[1])
task[2] = float(task[2])

或者用更复杂的方式

task = [ f(x) for (f, x) in zip([str, int, float], input().split()) ]

0
投票

是的,你可以这样做。试试这个。

>>> task = input().split()
hello 3 42.3
>>> task       # task is a list of strings
['hello', '3', '42.3']

# get the 3 parts of task

>>> string = task[0]
>>> int = int(task[1])
>>> float = float(task[2])
>>> string, int, float
('hello', 3, 42.3)

0
投票

虽然没有什么可用的方法,但你可以为它写一个自己的函数,比如这个。

def my_input(data_types):
    user_input = input()
    split_user_input = user_input.split()
    converted_input_tokens = []

    for input_token, data_type in zip(split_user_input, data_types):
        converted_input_tokens.append(data_type(input_token))

    return converted_input_tokens

它将完全按照你所举的例子来做(不多也不少)。你可以这样使用它。

>>> my_input((str, int, float))
1 2 3

Which will return:

['1', 2, 3.0]

当然,它还可以做得更通用。例如,你可以为输入提示符添加参数,即 sepmaxsplit 对于 str.split 函数中使用的方法等。

如果你对如何操作有疑问,可以看看官方文档中的 input, str.split 并对Python中的类型转换进行一些研究。


-1
投票

你可以明确地将每个输入定义为特定的类型。

© www.soinside.com 2019 - 2024. All rights reserved.