Python总结 二


mylist = ['aa','bb']

  1. 元素个数len(mylist)
  2. 追加元素mylist.append('cc')
  3. 插入元素mylist.insert(1,'dd')
  4. 删除并获得mylist.pop(1)


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

list.remove(x) Remove the first item from the list whose value is x. It is an error if there is no such item.

list.index(x) Return the index in the list of the first item whose value is x. It is an error if there is no such item.

list.count(x) Return the number of times x appears in the list.

list.sort(cmp=None, key=None, reverse=False) Sort the items of the list in place (the arguments can be used for sort customization, see sorted() for their explanation).

list.reverse() Reverse the elements of the list, in place.


>>> from collections import deque
>>> queue = deque(["Eric", "John", "Michael"])
>>> queue.append("Terry")           # Terry arrives
>>> queue.append("Graham")          # Graham arrives
>>> queue.popleft()                 # The first to arrive now leaves
>>> queue.popleft()                 # The second to arrive now leaves
>>> queue                           # Remaining queue in order of arrival
deque(['Michael', 'Terry', 'Graham'])


append(x) Add x to the right side of the deque.

appendleft(x) Add x to the left side of the deque.

clear() Remove all elements from the deque leaving it with length 0.

count(x) Count the number of deque elements equal to x. New in version 2.7.

extend(iterable) Extend the right side of the deque by appending elements from the iterable argument.

extendleft(iterable) Extend the left side of the deque by appending elements from iterable. Note, the series of left appends results in reversing the order of elements in the iterable argument.

pop() Remove and return an element from the right side of the deque. If no elements are present, raises an IndexError.

popleft() Remove and return an element from the left side of the deque. If no elements are present, raises an IndexError.

remove(value) Removed the first occurrence of value. If not found, raises a ValueError. New in version 2.5.

reverse() Reverse the elements of the deque in-place and then return None. New in version 2.7.

rotate(n) Rotate the deque n steps to the right. If n is negative, rotate to the left. Rotating one step to the right is equivalent to: d.appendleft(d.pop()). Deque objects also provide one read-only attribute:

maxlen Maximum size of a deque or None if unbounded.


sorted(iterable[, cmp[, key[, reverse]]])

cmp(e1, e2) 是带两个参数的比较函数, 返回值: 负数: e1 < e2, 0: e1 == e2, 正数: e1 > e2. 默认为 None, 即用内建的比较函数. key 是带一个参数的函数, 用来为每个元素提取比较值. 默认为 None, 即直接比较每个元素. reverse 是一个布尔值, 表示是否反转比较结果.

In general, the key and reverse conversion processes are much faster than specifying an equivalent cmp function. This is because cmp is called multiple times for each list element while key and reverse touch each element only once. Use functools.cmp_to_key() to convert an old-style cmp function to a key function.

The built-in sorted() function is guaranteed to be stable. A sort is stable if it guarantees not to change the relative order of elements that compare equal — this is helpful for sorting in multiple passes (for example, sort by department, then by salary grade).



>>> str_list = ['c123', 'a123', 'B123']
>>> sorted(str_list, key=str.lower)
>>> str_list = sorted(str_list, key=str.lower)
['a123', 'B123', 'c123']

这里我提示一点sorted方法并没有直接作用于目标列表,而是返回一个排序后的列表。如果你知道排序的是unicode对象列表,可以使用key=unicode.lower,或者key = lambda s: s.lower()


>>> def mycmp(a, b):
    return cmp(a.lower(), b.lower())

>>> str_list = ['c123', 'a123', 'B123']
>>> str_list.sort(mycmp)
>>> print str_list
['a123', 'B123', 'c123']

不知你发现没有,每两个元素进行比较都会执行两次lower()方法,如果列表中元素为n,那要执行多少次lower()?虽然不推荐这样做,但也给我们提供了一种思路,如果不是字符串列表,而是结构很复杂的数据列表,我们就可以采用这样方法 ##三个方法 filter(), map(), and reduce() There are three built-in functions that are very useful when used with lists: filter(), map(), and reduce().

filter(function, sequence) returns a sequence consisting of those items from the sequence for which function(item) is true. If sequence is a string or tuple, the result will be of the same type; otherwise, it is always a list. For example, to compute a sequence of numbers not divisible by 2 or 3:

>>> def f(x): return x % 2 != 0 and x % 3 != 0
>>> filter(f, range(2, 25))
[5, 7, 11, 13, 17, 19, 23]

map(function, sequence) calls function(item) for each of the sequence’s items and returns a list of the return values. For example, to compute some cubes:

>>> def cube(x): return x*x*x
>>> map(cube, range(1, 11))
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]

More than one sequence may be passed; the function must then have as many arguments as there are sequences and is called with the corresponding item from each sequence (or None if some sequence is shorter than another). For example:

>>> seq = range(8)
>>> def add(x, y): return x+y
>>> map(add, seq, seq)
[0, 2, 4, 6, 8, 10, 12, 14]

The fate of reduce()

in Python 3000filter(P, S) is almost always written clearer as [x for x in S if P(x)], and this has the huge advantage that the most common usages involve predicates that are comparisons, e.g. x==42, and defining a lambda for that just requires much more effort for the reader (plus the lambda is slower than the list comprehension). Even more so for map(F, S) which becomes [F(x) for x in S]. Of course, in many cases you'd be able to use generator expressions instead.filter(P, S) = [x for x in S if P(x)]map(F, S) = [F(x) for x in S] ##产生式

>>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]


>>> matrix = [
...     [1, 2, 3, 4],
...     [5, 6, 7, 8],
...     [9, 10, 11, 12],
... ]

The following list comprehension will transpose rows and columns:

>>> [[row[i] for row in matrix] for i in range(4)]
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

As we saw in the previous section, the nested listcomp is evaluated in the context of the for that follows it, so this example is equivalent to:

>>> transposed = []
>>> for i in range(4):
...     transposed.append([row[i] for row in matrix])
>>> transposed
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

del 删除 pop()的不同点是不返回值 可切片

[1, 66.25, 333, 333, 1234.5]
>>> del a[2:4]
>>> a
[1, 66.25, 1234.5]

unpacking The statement t = 12345, 54321, 'hello!' is an example of tuple packing: the values 12345, 54321 and 'hello!' are packed together in a tuple. The reverse operation is also possible:

>>> x, y, z = t


>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
>>> fruit = set(basket)               # create a set without duplicates
>>> fruit
set(['orange', 'pear', 'apple', 'banana'])
>>> 'orange' in fruit                 # fast membership testing
>>> 'crabgrass' in fruit

>>> # Demonstrate set operations on unique letters from two words
>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a                                  # unique letters in a
set(['a', 'r', 'b', 'c', 'd'])
>>> a - b                              # letters in a but not in b
set(['r', 'd', 'b'])
>>> a | b                              # letters in either a or b 并集
set(['a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'])
>>> a & b                              # letters in both a and b 交集
set(['a', 'c'])
>>> a ^ b                              # letters in a or b but not both 相异的部分
set(['r', 'd', 'b', 'm', 'z', 'l'])

Similarly to list comprehensions, set comprehensions are also supported:

>>> a = {x for x in 'abracadabra' if x not in 'abc'}
>>> a
set(['r', 'd'])

字典 查找速度快

>>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
{'sape': 4139, 'jack': 4098, 'guido': 4127}

In addition, dict comprehensions can be used to create dictionaries from arbitrary key and value expressions:

>>> {x: x**2 for x in (2, 4, 6)}
{2: 4, 4: 16, 6: 36}

When the keys are simple strings, it is sometimes easier to specify pairs using keyword arguments:

>>> dict(sape=4139, guido=4127, jack=4098)
{'sape': 4139, 'jack': 4098, 'guido': 4127}

遍历方法enumerate() 序号-》元组

>>> for i, v in enumerate(['tic', 'tac', 'toe']):
...     print i, v
0 tic
1 tac
2 toe

zip() 合并-》元组

>>> questions = ['name', 'quest', 'favorite color']
>>> answers = ['lancelot', 'the holy grail', 'blue']
>>> for q, a in zip(questions, answers):
...     print 'What is your {0}?  It is {1}.'.format(q, a)
What is your name?  It is lancelot.
What is your quest?  It is the holy grail.
What is your favorite color?  It is blue.

iteritems() 字典-》元组

>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
>>> for k, v in knights.iteritems():
...     print k, v
gallahad the pure
robin the brave

sorted 排序

>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
>>> for f in sorted(set(basket)):
...     print f

reversed() 反向

>>> for i in reversed(xrange(1,10,2)):
...     print i

Copy list[:] To change a sequence you are iterating over while inside the loop (for example to duplicate certain items), it is recommended that you first make a copy. Looping over a sequence does not implicitly make a copy. The slice notation makes this especially convenient:

>>> words = ['cat', 'window', 'defenestrate']
>>> for w in words[:]:  # Loop over a slice copy of the entire list.
...     if len(w) > 6:
...         words.insert(0, w)
>>> words
['defenestrate', 'cat', 'window', 'defenestrate']