繁体   English   中英

如何在单行中将不同的数据类型作为输入

[英]How to take different datatype as input in single line

我想使用单个输入行将字符串和整数作为输入,但解释器返回的错误'type' object is not iterable 这是我尝试的代码:

name, age = map(str, int, input("Enter the name and age \t").split())

您已经很亲密,可以随后进行投射:

name, age = input("Enter the name and age \t").split()
age = int(age)

您使用的map不正确。 如果您真的想在一行中执行此操作,则可以使用如下所示的lambda函数:

name, age = map(lambda x: int(x) if x.isdigit() else x, input("Enter the name and age \t").split())

不要使事情过于复杂。

name, age = input("Enter the name and age\t").split()
age = int(age)

问题在于, map期望一个可调用对象,然后是一个或多个可迭代值,具体取决于可调用对象期望有多少个参数。 可调用对象应用于每个可迭代对象中的一个元素,等效于

# result = list(map(f, x1, x2, ...))
result = [f(a1, a2, ...) for a1, a2, ... in zip(x1, x2, ...)]

您想要的是多个可调用对象,每个可调用对象都将应用于单个可迭代对象的不同元素:

name, age = [f(a) for f, a in zip([str, int], xs)]
name, age = [int(i) if i.isdigit() else i for i in input("Enter the name and age \t").split()]

注意:

你不能那样使用map功能

map()函数为iterable中的每个项目执行一个指定的函数。 该项目将作为参数发送到函数。

句法

 map(function, iterables) 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM