1. 从命名上,Python的List是一个链表,而它实际上是一个数组(Array)。更确切地说,它是一个动态数组,类似于C++的std::vector。
2. Slice
a[start:end] # items start through end-1
a[start:] # items start through the rest of the array
a[:end] # items from the beginning through end-1
a[:] # a copy of the whole array
另外,可以设定step:
a[start:end:step] # start through not past end, by step
start, end和step都可以是负数:
a[-1] # last item in the array
a[-2:] # last two items in the array
a[:-2] # everything except the last two items
当step是负数的时候,表示从后向前遍历:
a[::-1] # reverse a string
Slice时,start、end的值不同于index的值
Python indexes and slices for a six-element list.
Indexes enumerate the elements, slices enumerate the spaces between the elements.
Index from rear: -6 -5 -4 -3 -2 -1 a=[0,1,2,3,4,5] a[1:]==[1,2,3,4,5]
Index from front: 0 1 2 3 4 5 len(a)==6 a[:5]==[0,1,2,3,4]
+---+---+---+---+---+---+ a[0]==0 a[:-2]==[0,1,2,3]
| a | b | c | d | e | f | a[5]==5 a[1:2]==[1]
+---+---+---+---+---+---+ a[-1]==5 a[1:-1]==[1,2,3,4]
Slice from front: : 1 2 3 4 5 : a[-2]==4
Slice from rear: : -5 -4 -3 -2 -1 :
b=a[:]
b==[0,1,2,3,4,5] (shallow copy of a)
由于slice是两个元素之间的空间,可以用对slice赋值实现插入操作,比如:
>>> r=[1,2,3,4]
>>> r[1:1]
[]
>>> r[1:1]=[9,8]
>>> r
[1, 9, 8, 2, 3, 4]
>>> r[1:1]=['blah']
>>> r
[1, 'blah', 9, 8, 2, 3, 4]
http://stackoverflow.com/questions/509211/good-primer-for-python-slice-notation上可以看到更多讨论
3. 一个list由若干个sublist组成,把sublist里的元素抽出来形成一个新的list,比如:x = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]变成[1, 2, 3, 4, 5, 6, 7, 8, 9]
print [item for sumlist in x for item in sublist]
print sum(x, [])
print reduce(lambda m, n: m + n, x)
4. 和上题类似,不同的是sublist里可能还有sublist。怎么把这个嵌套的list变成一个普通的list,比如x=[[1, 2, [3, [4, 5], 6]], [7, 8], 9]变成[1, 2, 3, 4, 5, 6, 7, 8, 9]
def flatten(x):
if isinstance(x, collection.Iterable):
return [a for i in x for a in flatten(i)]
else:
return [x]
def flatten_2(x):
for sub in x:
if isinstance(sub, collections.Iterable):
for a in flatten_2(sub):
yield a
else:
yield sub
def flatten_3(l, ltypes=collections.Sequence):
l = list(l)
while l:
while l and isinstance(l[0], ltypes):
l[0:1] = l[0]
if l: yield l.pop(0)
5. 把一个list分成若干个长度为n的sublist(最后一个sublist长度可能小于n)。比如[1, 2, 3, 4, 5, 6, 7, 8] => [[1, 2, 3], [4, 5, 6], [7, 8]]
def group(l, n):
for i in range(0, len(l), n):
yield l[i:i+n]
6. 从List里删除符合某条件的数字:
L[:] = filter(lambda x: check(x), L)
或者:
L[:] = [x for x in L if check(x)]
7. Tuple非常适合交换两个数字:
a, b = b, a
8. Tuple也可以用来在函数里传出多个返回值:
def swap(x, y):
return y, x
a, b = swap(a, b)