Problem concatenating Python list

三世轮回 提交于 2019-12-10 10:52:13

问题


I am trying to concatenate two lists, one with just one element, by doing this:

print([6].append([1,1,0,0,0]))

However, Python returns None. What am I doing wrong?


回答1:


Use the + operator

>>> [6] + [1,1,0,0,0]
[6, 1, 1, 0, 0, 0]

What you were attempting to do, is append a list onto another list, which would result in

>>> [6].append([1,1,0,0,0])
[6, [1,1,0,0,0]]

Why you are seeing None returned, is because .append is destructive, modifying the original list, and returning None. It does not return the list that you're appending to. So your list is being modified, but you're printing the output of the function .append.




回答2:


For list concatenation you have two options:

newlist = list1 + list2

list1.extend(list2)



回答3:


use a list first (unless you really do not want to use your data in future )

>>> a=[6]
>>> a.append([1,1,0,0,0])
>>> a
[6, [1, 1, 0, 0, 0]]

another way is to use extend() instead of append()

>>> a=[6]
>>> a.extend([1,1,0,0,0])
>>> a
[6, 1, 1, 0, 0, 0]



回答4:


l1 = [6]
l2 = [1, 1, 0, 0, 0]
l1.extend(l2)
print l1
[6, 1, 1, 0, 0, 0]


来源:https://stackoverflow.com/questions/5203238/problem-concatenating-python-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!