Python报错:can only concatenate list (not "str") to list 原因解析
TypeError错误原因分析
原始可运行代码
result={} for i in range(1): a="Bug: from the English bug — bug, bug, bug in the program".split() result[a[0][0:-1]]=result.get(a[0][0:-1],[]) + [' '.join(a[1:])] # ' '.join(a[1:]) - error print(result)
修改后触发错误的代码
result={} for i in range(1): a="Bug: from the English bug — bug, bug, bug in the program".split() result[a[0][0:-1]]=result.get(a[0][0:-1],[]) + ' '.join(a[1:]) print(result)
触发错误:TypeError: can only concatenate list (not "str") to list
错误原因
result.get(a[0][0:-1], []) 返回的是列表类型——要么是该键已存在的列表值,要么是默认的空列表[]。而' '.join(a[1:])返回的是字符串类型。Python不允许直接将列表和字符串执行拼接操作,不同数据类型无法直接合并,因此抛出这个类型错误。
原始代码中将字符串用[]包裹成单元素列表,这样拼接的两边都是列表类型,自然可以正常执行操作。
内容的提问来源于stack exchange,提问作者Wismut
相关产品推荐
相关产品推荐

