Python-列表,,>>> L = [‘


>>> L = [‘spam‘, ‘Spam‘, ‘SPAM!‘]

>>> L[0:2] = [‘eat‘, ‘more‘]

>>> L

[‘eat‘, ‘more‘, ‘SPAM!‘]

========================================

>>> L[1:2] = [4,5]

>>> L

[‘eat‘, 4, 5, ‘SPAM!‘]

========================================

>>> L.append(‘please‘)

>>> L

[‘eat‘, 4, 5, ‘SPAM!‘, ‘please‘]

>>> L.sort()

TypeError

因为‘eat‘是String,而4, 5是int

========================================

使用append函数,执行起来要比"+"合并速度快,因为append函数不用生成新的对象。

L[len(L):] = [X] 与 L.append(X) 一样;

L[:0] = [X] 即在列表前端附加;

以上两者都会删除空分片,并插入X;

注意:append函数与sort函数,并没有返回值;

============================================

pop函数为删除并返回一个元素,默认返回最后一个;

>>> L = [‘spam‘, ‘eggs‘, ‘ham‘, ‘toast‘]

>>> L.remove(‘eggs‘)

>>> L

[‘spam‘, ‘ham‘, ‘toast‘]

>>> L.pop(1)

‘ham‘

>>> L

[‘spam‘, ‘toast‘]

=================================

Python-列表

评论关闭