问题描述
我有字典
name_dict = {'A':'1','B':'2','C':'3'}
newcols = []
for col in enhancer.columns:
if col in name_dict:
newcols.append(name_dict[col])
else:
newcols.append(col)
enhancer.columns = newcols
但是我得到的不是newcols = ['1','2','3']
,而是newcols = [['1'],['2'],['3']]
如何避免创建此列表列表,以便无需获得TypeError: unhashable type: 'list'
就可以更改列名称?
解决方法
[根据评论进行了更新]查看enhancer.columns
包含的内容将很有帮助。我认为是这样的:
class enhancer():
columns = ["A","B","C"]
从注释中听起来,name_dict
包含列表而不是字符串。例如:
name_dict = {'A':['1'],'B':['2'],'C':['3']}
结果是您的输出是列表列表。一些简单的修复方法是:
- 将
name_dict
更改为字符串字典(例如{'A': '1','B':'2','C':'3'}
) - 修改循环。例如:
name_dict = {'A':['1'],'C':['3']}
class enhancer():
columns = ["A","C"]
newcols = []
for col in enhancer.columns:
if col in name_dict:
# add the string to the list,rather than append
newcols += name_dict[col]
else:
# add the string to the list,rather than append
newcols += col
enhancer.columns = newcols
print(enhancer.columns)
输出:
['1','2','3']