Python 尝试将列表添加到列表时获取TypeError
这是我的代码:Python 尝试将列表添加到列表时获取TypeError,python,python-3.x,python-2.7,list,dictionary,Python,Python 3.x,Python 2.7,List,Dictionary,这是我的代码: 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])
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
。这个答案提供了更多细节:
从集合导入defaultdict
定义反向命令(d):
res=defaultdict(列表)
对于d.项()中的k,v:
res[v].追加(k)
返回res
打印(反向命令({'cc':'dd','ab':'cd','bb':'cd'}))
#defaultdict(,{'dd':['cc'],'cd':['ab','bb']})
打印(反方向({'b':'d','c':'d','a':'d'))
#defaultdict(,{'d':['b','c','a']})
对上述解决方案的解释
允许您为任意键指定默认值collections.defaultdict
- 在此实现中,默认值是空的
列表
- 因此,我们只需在输入字典中循环,并使用
将原始字典中的键添加到设置为新字典键的值中list.append
collections.defaultdict
解决此问题
代码的问题在于,要将列表中的元素添加到另一个列表中,您需要list.extend
而不是list.append
。这个答案提供了更多细节:
从集合导入defaultdict
定义反向命令(d):
res=defaultdict(列表)
对于d.项()中的k,v:
res[v].追加(k)
返回res
打印(反向命令({'cc':'dd','ab':'cd','bb':'cd'}))
#defaultdict(,{'dd':['cc'],'cd':['ab','bb']})
打印(反方向({'b':'d','c':'d','a':'d'))
#defaultdict(,{'d':['b','c','a']})
对上述解决方案的解释
允许您为任意键指定默认值collections.defaultdict
- 在此实现中,默认值是空的
列表
- 因此,我们只需在输入字典中循环,并使用
将原始字典中的键添加到设置为新字典键的值中list.append
>>> 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.extend(new_dict[new_key])
... new_list = sorted(new_list)
... new_dict[new_key] = new_list
... return new_dict
...
>>> print(inverse_dict({'cc': 'dd', 'ab': 'cd', 'bb': 'cd'}))
{'dd': ['cc'], 'cd': ['ab', 'bb']}
>>> print(inverse_dict({'b': 'd', 'c': 'd', 'a': 'd'}))
{'d': ['a', 'b', 'c']}
new\u dict
的值是列表。当您将一个列表附加到另一个列表时,会得到嵌套列表。您想通过另一个列表删除该列表:
>>> 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.extend(new_dict[new_key])
... new_list = sorted(new_list)
... new_dict[new_key] = new_list
... return new_dict
...
>>> print(inverse_dict({'cc': 'dd', 'ab': 'cd', 'bb': 'cd'}))
{'dd': ['cc'], 'cd': ['ab', 'bb']}
>>> print(inverse_dict({'b': 'd', 'c': 'd', 'a': 'd'}))
{'d': ['a', 'b', 'c']}
您正在将一个列表附加到一个列表中,该列表将其嵌套在其中。您应该将它们连接起来:
new_list += new_dict[new_key]
但更简单的方法是不创建新的列表,只将其附加到键中的列表
for new_key, new_value in enumerate(my_dict):
if new_value in new_dict:
new_dict[new_value].append(new_key)
new_dict[new_value] = sorted(new_dict[new_value])
else
new_dict[new_value] = [new_key]
这对于
defaultdict
来说也是一个很好的用法,因为您将一个列表附加到一个列表中,该列表嵌套在其中。您应该将它们连接起来:
new_list += new_dict[new_key]
但更简单的方法是不创建新的列表,只将其附加到键中的列表
for new_key, new_value in enumerate(my_dict):
if new_value in new_dict:
new_dict[new_value].append(new_key)
new_dict[new_value] = sorted(new_dict[new_value])
else
new_dict[new_value] = [new_key]
这也是一个很好的用法,因为下面的函数可以给出正确的结果:
def inverse_dict(dict_):
inverse_dict = dict() # Set an empty dictionary
for key, value in dict_.items():
try:
# If list, add key into list; otherwise it will throw exeption
inverse_dict[value].append(key)
except AttributeError:
# AttributeError means value has item but not list
inverse_dict[value] = [inverse_dict[value], key]
except KeyError:
# KeyError means there isn't any item in the new dictionary
inverse_dict[value] = key
return inverse_dict
下面的函数给出正确的结果:
def inverse_dict(dict_):
inverse_dict = dict() # Set an empty dictionary
for key, value in dict_.items():
try:
# If list, add key into list; otherwise it will throw exeption
inverse_dict[value].append(key)
except AttributeError:
# AttributeError means value has item but not list
inverse_dict[value] = [inverse_dict[value], key]
except KeyError:
# KeyError means there isn't any item in the new dictionary
inverse_dict[value] = key
return inverse_dict
当您尝试对
new\u list
进行排序时,可能会混合使用字符串和列表。请使用extend
而不是append
。Python 3不会尝试猜测您希望如何比较完全不同类型的对象。是否希望所有列表都位于所有字符串之前?在所有的弦乐之后?还是将字符串视为单元素字符串列表?无论您想要什么,您都可以为它编写一个键函数,并将其传递给排序后的
,但是你必须先决定你想要什么。误导性的标题…当你尝试排序new_list
时,你可能混合了字符串和列表。使用extend
而不是append
。Python 3不会试图猜测你想要如何比较完全不同类型的对象。是否希望所有列表都位于所有字符串之前?在所有的弦乐之后?还是将字符串视为单元素字符串列表?无论您想要什么,您都可以为它编写一个键函数,并将其传递给排序后的
,但您必须先决定您想要什么。标题。。。