如何解决ValueError: 以 10 为基数的 int() 的无效文字:对于 Python 中的 map(int, list) 错误
我正在尝试学习 python 中 map() 的功能
现在当我这样做时,
bits = ['and','2','3','1']
ports = map(int,bits)
#The below line is for the next iteration,where plus_net can be considered a counter
ports = [p+_plusnet for p in ports]
现在 bits 是这里的一个列表,当我尝试 map() 沿着端口迭代时,我收到错误,
ValueError: 以 10 为基数的 int() 的无效文字:'and'
不知道如何处理。 建议? 谢谢!
解决方法
bits = ['and','2','3','1']
ports = [int(s) if s.isdigit() else s for s in bits]
#OP request,get tuple
ports = ((ports[0],[port for port in ports[1:]]))
使用列表理解来检查您的列表元素是否符合 int
类型。如果是,请int()
,否则不要。
或者,删除不符合条件的元素:
bits = ['and','1']
ports = [int(s) for s in bits if s.isdigit()]
#The below line is for the next iteration,where plus_net can be considered a counter
ports = [p+_plusnet for p in ports]
,
bits = ['and','1']
def myint(a):
if a.isdigit():
return int(a)
else:
return 0
ports = map(myint,bits)
ports = [p+_plusnet for p in ports]
如果你想替换字符串字面量
,map(fun,iterable) => fun 将应用于 iterable 的每个元素。 有了这个逻辑。
映射(整数位) int('and') 会为以 10 为基数的 int() 抛出无效文字,因为您无法将字母文字直接转换为 int。
,# Lets do a lambda function to solve the problem and add a condition
# if there is a int value in bits list it will be added too
bits = ['and','1']
intplus = lambda i,p: \
(isinstance(i,str) and i.isdigit() and int(i)+p) or \
(isinstance(i,int) and i+p) or i
ports = [ intplus(p,_plusnet) for p in bits ]
# bits = ['and','1',5] will work too and 5 will be added
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。