python面...

python面试二《列表》:

2016-11-16  本文已影响6人  jackbom

1.所有的切片操作都会返回新的列表,包含求得的元素。这意味着以下的切片操作 返回列表 a 的一个浅复制副本

2.也可以对切片赋值,此操作可以改变列表的尺寸,或清空它

>>> # Replace some items:

... a[0:2] = [1, 12]

>>> a

[1, 12, 123, 1234]

>>> # Remove some:

... a[0:2] = []

>>> a

[123, 1234]

>>> # Insert some:

... a[1:1] = ['bletch', 'xyzzy']

>>> a

[123, 'bletch', 'xyzzy', 1234]

>>> # Insert (a copy of) itself at the beginning

>>> a[:0] = a

>>> a

[123, 'bletch', 'xyzzy', 1234, 123, 'bletch', 'xyzzy', 1234]

>>> # Clear the list: replace all items with an empty list

>>> a[:] = []

>>> a

[]

3.在迭代过程中修改迭代序列不安全(只有在使用链表这样的可变序列时才会有这 样的情况)。如果你想要

修改你迭代的序列(例如,复制选择项),你可以迭代 它的复本。使用切割标识就可以很方便的做到这一

>>> for x in a[:]: # make a slice copy of the entire list

if len(x) > 6: a.insert(0, x)

>>> a

['defenestrate', 'cat', 'window', 'defenestrate']

4.list.append(x)

Add an item to the end of the list; equivalent to a[len(a):] = [x].

把一个元素添加到链表的结尾,相当于 a[len(a):] = [x] 。

list.extend(L)

Extend the list by appending all the items in the given list; equivalent to a[len(a):] =

L.

将一个给定列表中的所有元素都添加到另一个列表中,相当于 a[len(a):] = L

上一篇下一篇

猜你喜欢

热点阅读