2013-02-08 37 views
0

我有了这样的结构的Python列表:转换嵌套的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的知识很薄弱,所以我希望有其他快速方法来转换这些数据...

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

+0

是否有一个原因,这是一个列表?它看起来应该是我的一个词典。 – RickyA 2013-02-08 22:07:25

+0

我只是没有真正了解python,但是,我肯定应该为这个应用程序使用字典。谢谢! – user1642475 2013-02-11 16:25:40

回答

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 
+0

谢谢!这绝对是我正在寻找的 - 在这种情况下使用翻译功能的价值是什么? – user1642475 2013-02-11 16:24:18

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%的数据将正确的位置。