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

Python实现字符串型氧化态列表转整数嵌套元组列表

问题场景

需要从元组 list1 = ('CaFe', 'BaSi', 'SeOs', 'BaGeO', 'CdCe') 中提取AB类化合物A、B组分的氧化态,初始编写的pandas处理代码如下:

dfA = pd.read_csv("oxi_state.csv",index_col=0, header =0)
A1 = []
A2 = []
final = []
for i in range(len(list1)):
   A1 = dfA['OS'][list1[i][0]]
   A2 = dfA['OS'][list1[i][1]]
   A = (A1, A2)
   final.append(A)
final

运行代码后得到的结果为字符串组成的元组列表,所有氧化态数值均为字符串类型,单元素对应多氧化态时会以逗号拼接为单个字符串,输出如下:

[('2', '2,3,4'),
 ('2', '4'),
 ('-2,4,6', '4,5,6,7'),
 ('2', '2,4'),
 ('2', '3,4')]
转换目标

需要将上述字符串格式结果转换为整数列表构成的元组列表,目标格式如下:

[([2], [2, 3, 4]),  ([2], [4]),  ([-2,4,6], [4,5,6,7]),  ([2], [2,4]),  ([2], [3,4])]
实现方法

核心逻辑是对每个氧化态字符串按逗号做拆分,再将拆分后的每个子串转换为整数,组装成对应结构即可,提供两种常用实现路径:

  • 对已生成的字符串格式结果做二次转换
converted_result = []
for a_os_str, b_os_str in final:
    # 拆分A位氧化态字符串并转为整数列表
    a_ox_states = [int(num) for num in a_os_str.split(',')]
    # 拆分B位氧化态字符串并转为整数列表
    b_ox_states = [int(num) for num in b_os_str.split(',')]
    converted_result.append( (a_ox_states, b_ox_states) )

如果需要更简洁的写法,也可以直接用列表推导式完成转换:

converted_result = [
    ([int(x) for x in a_str.split(',')], [int(x) for x in b_str.split(',')]) 
    for a_str, b_str in final
]
  • 直接修改初始取值逻辑,读取数据时同步完成转换,省去二次处理步骤
dfA = pd.read_csv("oxi_state.csv",index_col=0, header =0)
final = []
for formula in list1:
    a_ox = [int(os) for os in dfA['OS'][formula[0]].split(',')]
    b_ox = [int(os) for os in dfA['OS'][formula[1]].split(',')]
    final.append( (a_ox, b_ox) )

内容的提问来源于stack exchange,提问作者Neelesh Gupta

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 21:15:19