mysql - 如何使用Python最有效的方式将列表中可变数量的元素复制到统一列表并存储在MySQL中?

标签 mysql python

这是一个示例列表(每行都有可变元素):

['1', 'Tech', 'Code']
['2', 'Edu']
['3', 'Money', 'Sum', '176']

我必须将其插入到一个有 4 列的 MySQL 表中(列表中值的最大元素数)。

如何有效地做到这一点?我感觉我的解决方案效率最低!

这是我的解决方案:

for eachval in mylistings:       #mylistings has the sample list elements described above
     mylen = len(eachval)
     defaultlist = [None]*4   #reset defaultlist to 'None' to handle variable no. of columns
     ctr = 0
     for myoneval in mylistingline:
          defaultlist[ctr] = myoneval
          ctr += 1

for finalval in defaultlist:     #finally inserting them into a MySQL table
            cursor.execute("INSERT INTO LoadData VALUES (%s, %s, %s, %s)", (finalval[0], finalval[1], finalval[2], finalval[3]))

最佳答案

这个怎么样?

for line in mylistings:
    out = line + [None] * (4 - len(line)) # pad the list with None to 4 elements
    cursor.execute("INSERT INTO LoadData VALUES (%s, %s, %s, %s)", out)

关于mysql - 如何使用Python最有效的方式将列表中可变数量的元素复制到统一列表并存储在MySQL中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3915222/

相关文章:

python - TfIdf 矩阵返回 BernoulliNB 的特征数量错误

python - 导入错误: bad magic number in 'dateparser' : b'\x03\xf3\r\n'

python - 使用 boto3 读取指定文件夹/目录下 Amazon S3 文件夹上的表名称列表

python - TensorFlow 1.7 + Keras 和数据集 : Object has no attribute 'ndim'

php - 使用现有数据库数据将不可空列添加到 laravel 迁移

c++ - MySQL C++ 连接器未解析的外部

mysql - 错误代码: 1452 cannot add or update a child row a foreign key constraint fails mysql

mysql - 在不调用触发器的情况下在 mysql 中进行查询(如何禁用触发器)

php - 如何在php中获取标准输出json

python - 比在 python 中使用 if-else 语句更好的方法