【问题标题】:Adding different size of lists to database将不同大小的列表添加到数据库
【发布时间】:2021-10-02 22:11:02
【问题描述】:

我有一个 xml 文件。我想读取这个 xml 文件并使用 python 将其值添加到数据库中。到目前为止,我已经解析了数据。

import mysql.connector
import xml.etree.ElementTree as ET

dom = ET.parse('gg3.vmat')

tree = ET.parse('gg3.vmat')

root = tree.getroot()

parse_list = []

parse_list = root[0][0].text.split('\n')

removing_blank = [x.strip(' ') for x in parse_list]

removing_space = [x for x in removing_blank if x.strip()]


for material in root.findall('Material'):
    density = material.find('strings').text
    name = material.get('name')
    # print(name, density)

    parse_list = density.split('\n')

    removing_blank = [x.strip(' ') for x in parse_list]

    removing_space = [x for x in removing_blank if x.strip()]

    number = removing_space[0].split('=')[1]

    list = [c.split('=')[1] for c in removing_space[1:]]

    print(number, list)

解析返回的所有列表都有不同的大小。

列表示例:

[' Hydrogen', ' "0.02162"', ' Zirconium', ' "0.97838"']

[' Chromium', ' "0.000997"', ' Iron', ' "0.001994"', ' Oxygen', ' "0.001196"', ' Tin', ' "0.013955"', ' Zirconium', ' "0.981858"']

我想将此列表中的值添加到数据库中,如下所示:

我试图用 f-string 做一些事情,但我无法把它弄出来。

print([f'F#{list[i].strip()},{list[i]}' for i in range(len(list))])

感谢那些已经花时间的人。

【问题讨论】:

    标签: python python-3.x database list sqlite


    【解决方案1】:

    您需要成对地遍历列表。所以使用range(0, len(lst), 2) 迭代2。

    使用strip('" ') 删除数字周围的空格和引号。

    lst = [' Hydrogen', ' "0.02162"', ' Zirconium', ' "0.97838"']
    print('F#' + ''.join(f'{lst[i].strip()},{lst[i+1].strip('" ')} for i in range(0, len(lst), 2))]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-11
      • 2019-02-23
      • 1970-01-01
      相关资源
      最近更新 更多