这是一个示例列表(每行都有可变元素):
['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/