Home > Net >  Adding different size of lists to database
Adding different size of lists to database

Time:10-03

I have an xml file. I want to read this xml file and adding its values to database with python. I have already parsed the data so far.

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)

All of the lists that returned from parsing have different sizes.

Examples of lists:

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

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

I want to add the values in this list to the database as follows:

enter image description here

I tried to do something with f-string but I couldn't get it out.

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

Thank you to those who have already taken their time.

CodePudding user response:

You need to iterate through the list in pairs. So use range(0, len(lst), 2) to iterate by 2.

Use strip('" ') to remove spaces and quotes around the numbers.

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))]
  • Related