0

我有一个 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 的了解也很薄弱,所以我希望有其他快速的方法来转换这些数据......

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

4

2 回答 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% 地确保数据到达正确的位置。

于 2013-02-08T22:12:49.770 回答
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
于 2013-02-09T03:11:08.250 回答