将字典值追加到列表意外导致列表列表

问题描述

我有字典

name_dict = {'A':'1','B':'2','C':'3'}

我正在尝试使用以下循环重命名名称(A,B,C)在字典中的列

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']}

结果是您的输出是列表列表。一些简单的修复方法是:

  1. name_dict更改为字符串字典(例如{'A': '1','B':'2','C':'3'}
  2. 修改循环。例如:
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']