Why does adding to a list do different things?
本问题已经有最佳答案,请猛点这里访问。
1 2 3 4 5 6 7 8 9 10 11 | >>> aList = [] >>> aList += 'chicken' >>> aList ['c', 'h', 'i', 'c', 'k', 'e', 'n'] >>> aList = aList + 'hello' Traceback (most recent call last): File"<pyshell#16>", line 1, in <module> aList = aList + 'hello' TypeError: can only concatenate list (not"str") to list |
我不明白为什么做一个
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | >>> a = [] >>> a += 'asf' >>> a ['a', 's', 'f'] >>> a += (1, 2) >>> a ['a', 's', 'f', 1, 2] >>> d = {3:4} >>> a += d >>> a ['a', 's', 'f', 1, 2, 3] >>> a = a + d Traceback (most recent call last): File"<input>", line 1, in <module> TypeError: can only concatenate list (not"dict") to list |
要解决您的问题,您需要向列表中添加列表,而不是向列表中添加字符串。
试试这个:
1 2 3 4 | a = [] a += ["chicken"] a += ["dog"] a = a + ["cat"] |
请注意,它们都按预期工作。