2013-02-08 34 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%的數據將正確的位置。