Python内list添加内容

1. append() 追加单个元素到List的尾部,只接受一个参数,使用引号括起来的所有内容默认为字符,或者字符串,使用其他数据类型记得删掉引号。

 

>>>a=['a','b']
>>>a.append('c')
>>>a
['a','b','c']

>>> a = ['a','b','c']
>>> B = ['1','2','3']
>>> a.append('B')
>>> a.append(B)
>>> a
['a', 'b', 'c', 'B','1','2','3']

>>> C = {'name':123}
>>> a.append(C)
>>> a
['a', 'b', 'c', {'name': 123}]

>>> a.append('qwe')
>>> a
['a', 'b', 'c', 'qwe']

2. extend() 将一个列表中每个元素分别添加到另一个列表中,只接受一个参数;extend()相当于是将list B续接到list A的尾部。

 

>>> a = ['a','b','c']
>>> B = ['1','2','3']
>>> a.extend(B)
>>> a
['a', 'b', 'c', '1', '2', '3']
>>> a.extend('qwe')
>>> a
['a', 'b', 'c','q', 'w', 'e']

3. insert() 将一个元素插入到列表中,但其参数有两个(如insert(1,”g”)),第一个参数是索引点,即插入的位置,第二个参数是插入的元素。

 

>>>a
['a','b','c','d']
>>>a.insert(1,'x')
>>>a
['a','x','b','c','d']

4. + 加号,将两个list相加,会返回到一个新的list对象(仅仅限制在list数据格式),注意与前三种的区别。前面三种方法(append, extend, insert)可对列表增加元素的操作,他们没有返回值,是直接修改了原数据对象。 注意:将两个list相加,需要创建新的list对象,从而需要消耗额外的内存,特别是当list较大时,尽量不要使用“+”来添加list,而应该尽可能使用append()方法。

 

>>> a = ['a','b','c']
>>> B = ['1','2','3']
>>> C = {'name':123}
>>> d = a+b
>>> d
['a', 'b', 'c', '1', '2', '3']
>>> e = a+C
Traceback (most recent call last):
  File "<console>", line 1, in <module>
TypeError: can only concatenate list (not "dict") to list

猜你喜欢

转载自sodler.iteye.com/blog/2365039