Python 如果isinstance(x,list)附加列表中的新值会覆盖上一个值
我对Python完全是新手,尝试将我的一些东西自动化 我目前正试图找到一种方法,根据表本身的列为表创建字典Python 如果isinstance(x,list)附加列表中的新值会覆盖上一个值,python,Python,我对Python完全是新手,尝试将我的一些东西自动化 我目前正试图找到一种方法,根据表本身的列为表创建字典 cursor.execute(query) columns = [col[0] for col in cursor.description] rows = [dict(zip(columns, row)) for row in cursor.fetchall()] results = [] for row in rows: arg1 = row['arg1'] arg
cursor.execute(query)
columns = [col[0] for col in cursor.description]
rows = [dict(zip(columns, row)) for row in cursor.fetchall()]
results = []
for row in rows:
arg1 = row['arg1']
arg2 = row['arg2']
temp = row
temp['concat'] = (str(arg1) + str(arg2))
concat = row['concat']
def map_sth(x):
return {
'arg1arg2': ["abcd","efgh"],
'arg1arg2': "xyz",
}[str(x)]
mapped = map_sth(concat)
if isinstance(mapped, list):
for mapping in mapped:
temp['new_column'] = mapping
results.append(temp)
else:
temp['new_column'] = mapped
results.append(temp)
df = pandas.DataFrame(results)
df.to_csv("file.csv",index=False)
我调试了代码,它可以很好地处理map_sth中只有一项的结果
if isinstance(mapped, list):
for mapping in mapped:
temp['new_column'] = mapping
results.append(temp)
else:
temp['new_column'] = mapped
results.append(temp)
当它进入isinstance时,它为第一个循环提供了正确的值,但一旦进入第二个循环,它就会用map_sth中的第二个短语覆盖这两个值
如果您能为我提供任何帮助,我将不胜感激,因为我目前正陷于困境:/
谢谢 你的意思是说如果isinstance(映射,列表)<代码>地图是一种功能,您的
可以打印(行)
并展示给我们看吗?这样我们就可以自己尝试代码了。也请显示预期结果如果您对映射的每个值执行temp['new_column']=mapping
,那么您只是一遍又一遍地覆盖相同的值,它将包含您最后设置的值。当你将它添加到列表中时,它不会添加副本,它会添加对你已有词典的引用,因此你添加的每一个词典实际上都是相同的,具有相同的覆盖值。你的map\u sth
是无用的,不要创建一个只访问dict的方法,在外部定义dict,那就进入it@Kemp这正是问题所在,我该如何克服?