Skip to main content
 首页 » 编程设计

python之尝试将列表添加到列表时出现 TypeError

2025年05月04日20sharpest

这是我的代码:

def inverse_dict(my_dict): 
    new_dict = {} 
    new_key = '' 
    for new_value in my_dict: 
        new_list = [new_value] 
        new_key = my_dict[new_value] 
        if new_key in new_dict: 
            new_list.append(new_dict[new_key]) 
            new_list = sorted(new_list) 
        new_dict[new_key] = new_list 
    return new_dict 

还有我的主要内容:

def main(): 
    print(inverse_dict({'cc': 'dd', 'ab': 'cd', 'bb': 'cd'})) 
    print(inverse_dict({'b': 'd', 'c': 'd', 'a': 'd'})) 

我希望我的输入是:

  • 第一行 - {'cd': ['ab', 'bb'], 'dd': ['cc']}
  • 第二行 - {'d': ['a', 'b', 'c']}

但是我得到了错误,如果我删除了我对列表进行排序的行,我的输入看起来像:

  • 第一行 - {'dd': ['cc'], 'cd': ['bb', ['ab']]}
  • 第二行 - {'d': ['a', ['c', ['b']]]}

我能做什么?

请您参考如下方法:

你应该使用 collections.defaultdict 来解决这个问题。

您的代码的问题在于,要将一个列表的元素 添加到另一个列表,您需要list.extend 而不是list.append。这个答案提供了更多细节:

Difference between append vs. extend list methods in Python

from collections import defaultdict 
 
def inverse_dict(d): 
    res = defaultdict(list) 
    for k, v in d.items(): 
        res[v].append(k) 
 
    return res 
 
print(inverse_dict({'cc': 'dd', 'ab': 'cd', 'bb': 'cd'})) 
# defaultdict(<class 'list'>, {'dd': ['cc'], 'cd': ['ab', 'bb']}) 
 
print(inverse_dict({'b': 'd', 'c': 'd', 'a': 'd'})) 
# defaultdict(<class 'list'>, {'d': ['b', 'c', 'a']}) 

上述解决方案的解释

  • collections.defaultdict 允许您为任意键指定默认值。
  • 在此实现中,默认值为空 list。
  • 因此,我们只需遍历输入字典并使用 list.append 将原始字典中的键添加到设置为新字典键的值中。