将嵌套的 Python 列表转换为数据库

0 投票
2 回答
1067 浏览
提问于 2025-04-17 15:18

我有一个Python列表,它的结构像这样:

apts = [ [2083, \
           [ ["price", "$1000 / month"], \
             ["sq ft.", "500"], \
             ["amenities", "gym hardwood floor"]]], \
          [1096, \ 
           [ ["price", "$1200 / month"], \
             ["sq ft.", "700"], \
             ["a/c", "true"]]], \
          [76, \ 
           [ ["price", "$1100 / month"], \
             ["Pets", "true"], \
             ["a/c", "true"]]]] 

我想把它转换成一种格式,这样我就可以轻松地把它转移到MySQL数据库中。基本上,我想把它重新排列成类似表格或CSV文件的样子,这样就能方便地转移,比如:

id, price, sq ft, amenities, a/c, pets
2083, $1000 / month, 500, gym hardwood floor, ,
1096, $1200 / month, 700, , true,
76, $1100 / month, , true, true

提前谢谢你们。我能想到逐个映射这些数据的方法,但这看起来效率不高,而且我对Python的了解不深,所以我希望能找到其他快速的方法来转换这些数据……

如果我用嵌套字典结构,而不是嵌套列表,这样会有帮助吗?

2 个回答

1

我可能误解了问题,但如果你想把你的列表输出为CSV格式,你可以这样做:

import csv

out_file = open('/path/to/out_file.csv', 'wb')
writer = csv.writer(out_file, quoting=csv.QUOTE_ALL)
for data_row in apts:
    writer.writerow(data_row)

如果你想把数据导入到SQL数据库中(假设你的列表顺序是正确的,并且你已经正确处理了数据中的特殊字符),你可以使用以下方法:

import MySQLdb
mysql = MySQLdb.connect(host=host, user=user,passwd=passwd,db=db)
cursor = self.mysql.cursor()
queries = []
for row in apts:
    queries.append("('%s')" % "','".join(row) ) #< this will join the data encapsuled in apostrophes
cursor.execute( "INSERT INTO TABLE VALUES %s" % ",".join(queries) ) #< Insert the data

我强烈建议使用字典来处理这些数据,这样可以确保数据100%准确地放到正确的位置。

1

我理解你的问题是,你在把复杂的结构转换成一串字符串时遇到了困难。下面是一个可以实现的方法:

from collections import OrderedDict

out = []

for r in apts:
    row = OrderedDict([('id',''), ('price',''), ('sqft',''), 
                       ('amenities',''),('ac',''),('pets','')])        
    row['id']=r[0]
    for sr in r[1]:
        row[sr[0].lower().translate(None," ./")]=sr[1]
    out.append(row)

#print result        
for o in out:
    s = ",".join(map(str, o.values()))
    print s

打印输出

2083,$1000 / month,500,gym hardwood floor,,
1096,$1200 / month,700,,true,
76,$1100 / month,,,true,true

撰写回答