Python列表附加多个元素 [英] Python list append multiple elements
本文介绍了Python列表附加多个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想一次将多个元素添加到列表中.我尝试过
I want to append multiple elements to my list at once. I tried this
>>> l = []
>>> l.append('a')
>>> l
['a']
>>> l.append('b').append('c')
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
l.append('b').append('c')
AttributeError: 'NoneType' object has no attribute 'append'
>>>
如何同时添加'b'
和'c'
?
推荐答案
方法append()
在适当的地方有效.换句话说,它会修改列表,而不会返回新列表.
The method append()
works in place. In other words, it modifies the list, and doesn't return a new one.
因此,如果l.append('b')
不返回任何内容(实际上它返回None
),则您不能这样做:
So, if l.append('b')
doesn't return anything (in fact it returns None
), you can't do:
l.append('b').append('c')
因为它将等同于
None.append('c')
回答:我如何一次附加'b'和'c'?
您可以通过以下方式使用extend()
:
You can use extend()
in the following way:
l.extend(('b', 'c'))
这篇关于Python列表附加多个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文