转载

The Python Tutorial 阅读笔记

The Python Tutorial 是很好的学习资源,之前已经粗略的读过一遍,有不少细节性的东西都被略过了,这次详细地阅读一遍,顺便记录一些笔记,以供之后参考使用

Data Structures

More on Lists

  • list.append(x) : Equivalent to 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
  • list.insert(i, x) : The first argument is the index of the element before which to insert. a.insert(len(a), x) == a.append(x) .
  • list.remove(x) : Remove the first item form the list whose value is x.
  • list.pop([i]) : Remove the item at the given position in the list, and return it. If no index is specified, a.pop() removes and returns the last item in the list.(参数中的方括号表明参数是可选的)
  • list.clear() : Remove all item from the list. Equivalent to del a[:]
  • list.index(x) : Return the index in the list of the first item whose value is x.
  • list.count(x) : Return the number of times x appears in the list.
  • list.sort(key=None, reverse=False) : Sort the items of the list in place.
  • list.reverse() : Reverse the elements of the list in place.
  • list.copy() : Return a shallow copy of the list. Equivalent to a[:] .

Using Lists as Stacks

Use append and pop .

Using Lists as Queues

Lists are not efficient for this purpose. While appends and pops from the end of list are fast, doing inserts or pops from beginning of a list is slow.

Better to use collections.deque .

List Comprehensions

  • x = [item for item in series]
  • x = [do_something(item) for item in series if expression]

Nested List Comprehensions

The initial expression in a list comprehension can be any arbitrary expression, including another list comprehension.

Example: [[row[i] for row in matrix] for i in range(4)] .

The del statement

Remove an item from a list given its index. (Do not return a value) It can also remove slices from a list.

del can also be used to delete entire variables: del a .

Tuples and Sequences

Tuples are immutable , and usually contain a heterogeneous sequence of elements that are accessed via unpacking or indexing. List are mutable , and their element are usually homogeneous and are accessed by iterating over the list.

  • Empty tuples are constructed by and empty pair of parentheses: empty = ()
  • A tuple with one item is constructed by following a value with a comma: sigleton = 'hello',

The statement t = 1, 2, 'hello' is an example of tuple packing : the values are packed together in a tuple. The reverse operation is also possible: x, y, z = t .

Sets

{} or set() function can be used to create sets. Note: to create an empty set you have to use set() , not {} ; the latter creates an empty dictionary.

Example:

a = set('abracadabra')
b = set('alacazam')
  • a - b : letters in a but not in b
  • a | b : letters in either a or b
  • a & b : letters in both a and b
  • a ^ b : letters in a or b but not both

Similaryly to list comprehensions, set comprehensions are also supported.

Dictionaries

Dictionaries are indexed by keys, which can be any immutable type; strings and numbers can slways be keys. Tuples can be used as keys if they contain only one kind of item. You can’t use use lists as keys, since lists can be modified in place using index assignments, slice assignments, or method like append() and extend().

It is best to think of a dictionary as an unordered set of key: value pairs.

  • del can delete a key: value
  • list(d.keys()) on a dictionary returns a list of all the keys used in the dictionary, in arbitrary order (if you want it sorted, use sortted(d.keys()) instead).
  • To check whether a single key is in the dictionary, use the in keyword. ( in or not in )
  • Dict comprehensions can be used to create dictionaries from arbitrary key and value expressions: {x: x**2 for x in range(10)}
  • When the keys are simple strings, it is sometimes easier to specify pairs using keyword arguments: dic(sape=1, guido=2, jack=3) => {'sape': 1, 'jack': 3, 'guido': 2}

Looping Techniques

When looping through dictionaries, the key and corresponding value can be retrieved at the same time using the items() method.

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

When looping through a sequence, the position index and correspoding value can be retrieved at the same time using the enumerate() function.

for i, v in enumerate(['tic', 'tac', 'toe']):
print(i, v)

To loop over two or more sequences at the same time, the entries can be paired with the zip() function.

numbers = [1, 2, 3]
names = ['one', 'two', 'three']
for number, name in zip(numbers, names):
print('Number: {0}, Name: {1}'.format(number, name))

To loop over a sequence in sorted order, use the sorted() function which return a new sorted list while leaving the source unaltered. for item in soted(list)

It is sometimes tempting to change a list while you are looping over it; however, it is often simple and safer to create a new list instead.

More on Conditions

  • in and not in : check whether a value occurs (or not) in a sequence.
  • is and is not : compare whether two objects are really the same object; this only matters for mutable objcts like lists.
  • Comparisons can be chained. a < b == c
  • and and or are short-circuit operators
原文  http://forrestchang.github.io/2016/07/17/the-python-tutorial/
正文到此结束
Loading...