是否有更好的方法将列数据存储到Python列表中

时间:2019-04-30 15:38:58

标签: python python-3.x python-2.7 jupyter-notebook

我将列数据存储到Python列表中,列表名称应与列名称相同。

我正在使用以下代码:

import mysql.connector as mysql

db = mysql.connect(
    host = "localhost",
    user = "root",
    passwd = "",
    database = "DB"
)
cursor = db.cursor()
query = "SELECT * FROM sample1"
cursor.execute(query)
records = cursor.fetchall()

########  LIST ALL THE COLUMNS ######### 
field_names = [i[0] for i in cursor.description]

#Creating list with column name
for col in field_names:
    exec(col + "=[]")

#appending records into list
for record in records:
    first_name.append(record[0])
    last_name.append(record[1])
    full_name.append(record[2])

如果以后需要添加新列,则必须再次添加“ abc.append(record [3])”。

有什么方法可以动态创建列表并将数据追加到列表中吗?

谢谢

0 个答案:

没有答案