gpt4 book ai didi

Python - 使用 map(sys.stdin.readline()) 存储一个字符串和一个 int

转载 作者:太空狗 更新时间:2023-10-29 21:23:57 26 4
gpt4 key购买 nike

如果输入包含一个空格分隔的 int 行,比如-

1 3

我可以使用 map() 函数将其映射存储在数组中

arr = map(int,sys.stdin.readline().split())

或者甚至在两个独立的变量中,通过

n,m = map(int,sys.stdin.readline().split())

有没有办法用同样的方式读取包含混合数据类型的输入行。例如-

foo 3

foo 是字符串,3 是整数?

最佳答案

如果你总是有一个字符串和非负整数:

import sys
n, m = map(lambda x: (str, int)[x.isdigit()](x) ,sys.stdin.readline().split(None, 1))


print(n,m)

但最安全的方法是在转换用户输入时始终使用 try/except,即使只期望一种类型。

可以根据要求检查是否为负值:

import sys
n, m = map(lambda x: (str, int)[x.isdigit() or x.strip("-").isdigit()](x) ,sys.stdin.readline().split())


print(n, m)

但是 --10 --10-- 也将通过测试但会导致错误,因此仅针对您的特定情况。

关于Python - 使用 map(sys.stdin.readline()) 存储一个字符串和一个 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30406523/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com