You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python元素周期表项目:输入转float类型导致空列表问题排查

元素周期表查询项目:float类型查询返回空列表的解决方法

我正在开发一个元素周期表查询项目,用户输入元素的符号、原子序数或原子量(例如碳可通过C、12.011或6识别),程序会返回该元素的完整信息。目前已实现将输入转为int类型的逻辑,但添加float类型转换逻辑后,程序返回空列表,求解决。

原代码

from periodicTable import elements

givenInfo = input("please enter an the information you were given about the element, and I will enter the info for it:") #prompt for what they were provided

#makes an entry of 2 characters or less capitalized
if len(givenInfo) <= 2:
    givenInfo = givenInfo.capitalize()
if len(givenInfo) <= 3 and givenInfo.isdigit() == True:
    givenInfo = int(givenInfo)

#elif len(givenInfo) > 3 and givenInfo.isdigit() == True:
#    givenInfo = float(givenInfo)

#The proper designations for the data, for the start, it is all empty
name = ""
symbol = ""
atomNum = 0
atomMass = 0

#Loop to run through elements dictionry and make list of the values there
result = []
for element, element_dict in elements.items(): #for (new variable made in for loop), () in (dictionary elements, but .items() designates just the values)
    if (givenInfo in element_dict):
        result = list(element_dict)
        break
print(result)

#Loop to assign each value to its proper designation
i=0
while i < len(result):
    if type(result[i]) is int:
        atomNum = result[i]
        print("The atomic number is:", atomNum)
        i+=1
    elif type(result[i]) is float:
        atomMass = result[i]
        print("The atomic mass is:", atomMass)
        i+=1
    elif type(result[i]) is str and len(result[i]) > 2:
        name = result[i]
        print("The element name:", name)
        i+=1
    elif type(result[i]) is str and len(result[i]) <= 2:
        symbol = result[i]
        print("The symbol for the element:", symbol)
        i+=1
    else:
        print(type(result[i]))
        i+=1

元素字典结构

elements = {
    'hydrogen': {'hydrogen', 'H', 1, 1.0080}, 
    'helium': {'helium', 'He', 2, 4.0026},  
    'lithium': {'lithium', 'Li', 3, 7.0000}, 
    'beryllium': {'beryllium', 'Be',  4, 9.0121}, 
    'boron': {'boron', 'B', 5, 10.81}, 
    'carbon': {'carbon', 'C', 6, 12.011}, 
    'nitrogen': {'nitrogen', 'N', 7, 14.007}
}

问题原因

  1. 浮点数输入转换逻辑错误:givenInfo.isdigit()无法识别带小数点的字符串(比如"12.011"),所以注释的float转换代码永远不会执行,输入的原子量字符串无法转为float类型,自然匹配不到字典里的float值。
  2. 浮点数精度问题:即使成功转为float,直接用in判断会因为浮点数存储精度误差失败(比如输入的12.011和字典里的12.011可能在内存中存储值有细微差异)。
  3. 集合无序性隐患:元素信息存在集合中,集合是无序的,原代码的while循环依赖集合转列表后的顺序提取信息,逻辑不稳定。

解决方案

修改输入处理逻辑,正确转换浮点数;对浮点数匹配使用近似比较;优化元素信息提取方式,不依赖集合顺序。

修改后的完整代码

from periodicTable import elements

givenInfo = input("请输入元素的符号、原子序数或原子量:")

# 处理输入转换:优先转int,失败转float,最后处理字符串
processed_input = givenInfo
try:
    processed_input = int(givenInfo)
except ValueError:
    try:
        processed_input = float(givenInfo)
    except ValueError:
        # 处理元素符号:长度<=2时首字母大写
        if len(givenInfo) <= 2:
            processed_input = givenInfo.capitalize()
        else:
            processed_input = givenInfo.lower()

name = ""
symbol = ""
atom_num = 0
atom_mass = 0
result_found = False

# 遍历元素字典,匹配输入
for element_name, element_data in elements.items():
    match = False
    # 处理不同类型的输入匹配
    if isinstance(processed_input, int):
        # 匹配原子序数
        match = processed_input in element_data
    elif isinstance(processed_input, float):
        # 匹配原子量:允许0.0001的精度误差
        for item in element_data:
            if isinstance(item, float) and abs(item - processed_input) < 0.0001:
                match = True
                break
    else:
        # 匹配元素名称或符号
        match = processed_input in element_data
    
    if match:
        # 从集合中提取各字段信息
        for item in element_data:
            if isinstance(item, int):
                atom_num = item
            elif isinstance(item, float):
                atom_mass = item
            elif len(item) <= 2:
                symbol = item
            else:
                name = item
        result_found = True
        break

if result_found:
    print(f"元素名称:{name}")
    print(f"元素符号:{symbol}")
    print(f"原子序数:{atom_num}")
    print(f"原子量:{atom_mass}")
else:
    print("未找到匹配的元素,请检查输入内容")

关键修改说明

  • 输入转换:用try-except结构依次尝试转int、float,避免isdigit()的局限性,同时统一元素名称为小写,符号为首字母大写,提升匹配成功率。
  • 浮点数匹配:放弃直接in判断,改为遍历集合中的float值,用精度误差范围(0.0001)判断近似相等,解决精度问题。
  • 信息提取:遍历集合时直接根据类型和长度分配对应变量,不依赖集合顺序,逻辑更可靠。

内容的提问来源于stack exchange,提问作者Ian Schaak

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 05:04:54