2024-04-20 00:41:06 发布
网友
我想知道是否有一种更优雅的/pythonic的方法可以获得与以下代码相同的结果:
num1, num2, string = input().split() num1 = int(num1) num2 = int(num2)
其中num1(1<;=num1<;=15)和num2(5<;=num2<;=100)是整数,string是只由大写字母组成的字符串。在
您可以预先定义各个类型的序列,并使用zip(在python3中)直接转换它们。在
zip
types = (int, int, str) num1, num2, string = (typ(value) for typ, value in zip(types, input().split()))
input_string = "1 2 rand_string" num1, num2, string = [ int(i) if i.isdigit() else i for i in input_string.split() ]
对于map()和str.isdigit()函数,假设输入只需要严格顺序的整数和文本值:
map()
str.isdigit()
num1, num2, str1 = map(lambda x: x if not x.isdigit() else int(x), input().split()) print(type(num1), type(num2), type(str1))
输出(对于输入"10 55 hello"):
"10 55 hello"
您可以预先定义各个类型的序列,并使用
zip
(在python3中)直接转换它们。在对于
map()
和str.isdigit()
函数,假设输入只需要严格顺序的整数和文本值:输出(对于输入
^{pr2}$"10 55 hello"
):相关问题 更多 >
编程相关推荐