Python:从列表提取值得到单元素列表而非float类型的问题求助
解决方法
问题根因
你使用的tileAverages是嵌套列表结构,每一个位置存储的不是单独的浮点数,而是包裹了单个浮点数的子列表,因此遍历取出的tmpAvg自然为列表类型,无法直接参与数值运算。
可直接落地的修正方案
方案1:修改当前遍历逻辑,直接取出子列表内的浮点数
只需要在取元素时多取一层索引即可,同时注意提前初始化temp变量为无穷大避免初始值报错:
# 提前初始化临时变量 temp = float('inf') bestValue = 0 for loop in range(len(tileAverages)): # 多取[0]拿到子列表里的浮点数 tmpAvg = tileAverages[loop][0] if abs(sourcePixel - tmpAvg) < temp: temp = abs(sourcePixel - tmpAvg) bestValue = tmpAvg
方案2:先将嵌套列表拍平为一维浮点数列表
如果后续还要多次使用tileAverages,可以先统一做格式转换,后续所有逻辑都不需要再额外处理嵌套结构:
# 拍平嵌套列表 tileAverages = [item[0] for item in tileAverages] # 后续你原来的代码即可正常运行 temp = float('inf') bestValue = 0 for tmpAvg in tileAverages: if abs(sourcePixel - tmpAvg) < temp: temp = abs(sourcePixel - tmpAvg) bestValue = tmpAvg
方案3:更简洁的内置函数实现
不需要手写循环,直接用min()函数的自定义排序规则参数,一行即可得到结果:
# 未拍平嵌套列表的写法,返回的是子列表,要取浮点数加[0]即可 best_value_list = min(tileAverages, key=lambda x: abs(sourcePixel - x[0])) best_value = best_value_list[0] # 已经拍平为一维列表的写法 best_value = min(tileAverages, key=lambda x: abs(sourcePixel - x))
补充说明
你之前尝试强制类型转换无效的原因是:Python不支持直接将列表类型转换为数值类型,必须先取出列表内的数值元素,再做类型转换操作。
内容的提问来源于stack exchange,提问作者Stuart Fish
相关产品推荐
相关产品推荐

