您的位置:首页 > 编程语言 > Python开发

Python学习总结之三

2011-12-19 16:53 483 查看
 
Unpacking Argument Lists

        1、  write the function call with the *-operator to unpack the arguments out of a list or tuple。使用*操作符来分离List或元组的参数

>>> list(range(3, 6))            # normal call with separate arguments

[3, 4, 5]

>>> args = [3, 6]

>>> list(range(*args))            # call with arguments unpacked from a list

[3, 4, 5]

        2、In the same fashion, dictionaries can deliver keyword arguments with the **-operator  使用**操作符分离dictionary

>>> def parrot(voltage, state='a stiff', action='voom'):

...     print("-- This parrot wouldn't", action, end=' ')

...     print("if you put", voltage, "volts through it.", end=' ')

...     print("E's", state, "!")

...

>>> d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}

>>> parrot(**d)

-- This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised !

        3、Lambda Forms   匿名形式

Here’s a function that returns the sum of its two arguments: lambda a, b: a+b.

>>> def make_incrementor(n):

...     return lambda x: x + n

...

>>> f = make_incrementor(42)

>>> f(0)

42

>>> f(1)

43

        4、Documentation Strings

Here are some conventions about the content and formatting of documentation strings

1、The first line should always be a short, concise summary of the object’s purposeThis line should begin with a capital letter and end with a period.  第一行是大写字母开头,句号结尾

2、the second line should be blank,显示的分离

Intermezzo: Coding Style   代码样式

1、Use 4-space indentation, and no tabs      使用4个空格缩进

2、Wrap lines so that they don’t exceed 79 characters。自动换行。不超过79字符。

3、Use blank lines to separate functions and classes, and larger blocks of code inside functions。使用空白行分离函数和类。

在函数内部的大块代码。

4、When possible, put comments on a line of their own。当可能

5、Use spaces around operators and after commas, but not directly inside bracketing constructs: a = f(1, 2) + g(3, 4).

在逗号的后面和操作符周围使用空格,但是不要直接在括号的里面使用空格

6、Name your classes and functions consistently; the convention is to use CamelCase for classes and lower_case_with_underscores for functions and methods. Always use self as the name for the first method argument (see A First Look at Classes for more on classes
and methods). 命名你的类和函数,驼峰式和小写的样式

7、Don't use fancy encodings if your code is meant to be used in international environments. Python’s default, UTF-8, or even plain ASCII work best in any case. 如果使用在国际环境中,请使用合适的编码。UTF-8,或者ASCII比较好

8、Likewise, don’t use non-ASCII characters in identifiers if there is only the slightest chance people speaking a different language will read or maintain the code. 同样的,不要是非ASCII字符

Data Structures

More on Lists

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

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.   如果没有使用index索引,这返回最后一个元素。

Using Lists as Stacks

The list methods make it very easy to use a list as a stack,where the last element added is the first element retrieved

last-in, first-out。

To add an item to the top of the stack, use append(). To retrieve an item from the top of the stack, use pop() without an explicit index

添加使用append(),获取top元素,使用pop()

先进后出

Using Lists as Queues

先进先出       To implement a queue, use collections.deque which was designed to have fast appends and pops from both ends

To implement a queue, use collections.deque which was designed to have fast appends and pops from both ends。

为了实现了一个队列。使用了collections.deque.

>>> 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

'Eric'

>>> queue.popleft()                 # The second to arrive now leaves

'John'

>>> queue                           # Remaining queue in order of arrival

deque(['Michael', 'Terry', 'Graham'])

List Comprehensions 列表内涵,需要将for和if语句应用到极致

1、A list comprehension consists of brackets containing an expression followed by a for clause, then zero or more for or if clauses. 列表理解包含了for,或者零个或多个for或if语句。

>>> vec = [2, 4, 6]

>>> [3*x for x in vec]

[6, 12, 18]

2、Now we get a little fancier:   x**2   x多少次方  

>>> [[x, x**2] for x in vec]

[[2, 4], [4, 16], [6, 36]]

3、Here we apply a method call to each item in a sequence:  使用strip函数清理左右空格

>>> freshfruit = ['  banana', '  loganberry ', 'passion fruit  ']

>>> [weapon.strip() for weapon in freshfruit]

['banana', 'loganberry', 'passion fruit']

4、Using the if clause we can filter the stream:

>>> [3*x for x in vec if x > 3]

[12, 18]

>>> [3*x for x in vec if x < 2]

[]

5、Tuples can often be created without their parentheses, but not here  数组不用括号被创建。但是这里要添加括号

>>> [x, x**2 for x in vec]  # error - parens required for tuples

  File "<stdin>", line 1, in ?

    [x, x**2 for x in vec]

               ^

SyntaxError: invalid syntax

>>> [(x, x**2) for x in vec]        

[(2, 4), (4, 16), (6, 36)]

6、Here are some nested for loops and other fancy behavior

>>> vec1 = [2, 4, 6]

>>> vec2 = [4, 3, -9]

>>> [x*y for x in vec1 for y in vec2]

[8, 6, -18, 16, 12, -36, 24, 18, -54]

>>> [x+y for x in vec1 for y in vec2]

[6, 5, -7, 8, 7, -5, 10, 9, -3]

>>> [vec1[i]*vec2[i] for i in range(len(vec1))]

[8, 12, -54]

7、List comprehensions can be applied to complex expressions and nested functions:

>>> [str(round(355/113, i)) for i in range(1, 6)]

['3.1', '3.14', '3.142', '3.1416', '3.14159']

Nested List Comprehensions

If you’ve got the stomach for it, list comprehensions can be nested. They are a powerful tool but – like all powerful tools – they need to be used carefully, if at all.  这是一个很强大的工具,因此需要小心使用它。

Special care has to be taken for the nested list comprehension:

        To avoid apprehension when nesting list comprehensions, read from right to left.  从右往左

The zip() function would do a great job for this use case。内置zip()函数

>>> list(zip(*mat))

[(1, 4, 7), (2, 5, 8), (3, 6, 9)]

The del statement

There is a way to remove an item from a list given its index instead of its value: the del statement

This differs from the pop() method which returns a value.    和pop()有不同,del不会返回值

The del statement can also be used to remove slices from a list or clear the entire list  删除slices和整个list

>>> a = [-1, 1, 66.25, 333, 333, 1234.5]

>>> del a[0]

>>> a

[1, 66.25, 333, 333, 1234.5]

>>> del a[2:4]

>>> a

[1, 66.25, 1234.5]

>>> del a[:]

>>> a

[]

Tuples and Sequences  元组和序列

We saw that lists and strings have many common properties, such as indexing and slicing operations

There is also another standard sequence data type: the tuple

A tuple consists of a number of values separated by commas, for instance:

元组就是用逗号分隔开来的一些值组成。

>>> t = 12345, 54321, 'hello!'

>>> t[0]

12345

>>> t

(12345, 54321, 'hello!')

>>> # Tuples may be nested:

... u = t, (1, 2, 3, 4, 5)

>>> u

((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))

As you see, on output tuples are always enclosed in parentheses 。tuples使用圆括号包围

Tuples have many uses. For example: (x, y) coordinate pairs, employee records from a database, etc. 经常使用在定义(x,y)和数据库的员工记录。

Tuples, like strings, are immutable。tuples和字符串是不可改变的。这不想List,可以通过修改index索引来修改它的值

A special problem is the construction of tuples containing 0 or 1 items: the syntax has some extra quirks to accommodate these. Empty tuples are constructed by an empty pair of parentheses; a tuple with one item is constructed by following a value with a comma
(it is not sufficient to enclose a single value in parentheses). Ugly, but effective. For example:  一个特殊的问题。就是包含0个或者1个元素时候,语法解析会有怪异。 空元组用圆括号包围。

一个元素是由一个值跟着一个逗号。

>>> empty = ()

>>> singleton = 'hello',    # <-- note trailing comma

>>> len(empty)

0

>>> len(singleton)

1

>>> singleton

('hello',)

Sets  集合

A set is an unordered collection with no duplicate elements  无序和无重复元素的集合

Set objects also support mathematical operations like union, intersection, difference, and symmetric difference.

支持union联合、intersection交集、difference差分,symmetric difference对称差分

Curly braces   大括号

Curly braces or the set() function can be used to create sets.   大括号和set()函数来创建sets

Note: To create an empty set you have to use set(), not {}; the latter creates an empty dictionary, a data structure that we discuss in the next section.  如果要创建空集合,必须使用set(),而不是{}。

>>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}

>>> print(basket)                      # show that duplicates have been removed

{'orange', 'banana', 'pear', 'apple'}

>>> 'orange' in basket                 # fast membership testing

True

>>> 'crabgrass' in basket

False

>>> # Demonstrate set operations on unique letters from two words

...

>>> a = set('abracadabra')

>>> b = set('alacazam')

>>> a                                  # unique letters in a

{'a', 'r', 'b', 'c', 'd'}

>>> a - b                              # letters in a but not in b     求差集

{'r', 'd', 'b'}

>>> a | b                              # letters in either a or b   或运算

{'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}

>>> a & b                              # letters in both a and b   并运算

{'a', 'c'}

>>> a ^ b                              # letters in a or b but not both   异或运算

{'r', 'd', 'b', 'm', 'z', 'l'}

2、Like for lists, there is a set comprehension syntax

>>> a = {x for x in 'abracadabra' if x not in 'abc'}

>>> a

{'r', 'd'}

Dictionaries

字典

1、Another useful data type built into Python is the dictionary  (Mapping types)

Dictionaries are sometimes found in other languages as “associative memories” or “associative arrays”

联想记忆和联想数组

dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys

字典是通过keys索引的,它是不可能变类型。字符串和数字总是能为keys

Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key.

如果他们包含的只有字符串和数字,或者元组,则元组就是可以使用作为keys。但是如果一个元组直接或间接的包含了可变的对象。则它就不能作为key。

You can’t use lists as keys, since lists can be modified in place using index assignments, slice assignments, or methods like append() and extend().

你不能使用list作为keys,因为list是可以被修改的,slice,append,extend操作。

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

Performing 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, just use sorted(d.keys()) instead). [1] To check whether a single key is in the dictionary, use the in keyword.

执行list(d.keys())返回所有无序的keys。sorted()排序。

>>> tel = {'jack': 4098, 'sape': 4139}

>>> tel['guido'] = 4127

>>> tel

{'sape': 4139, 'guido': 4127, 'jack': 4098}

>>> tel['jack']

4098

>>> del tel['sape']

>>> tel['irv'] = 4127

>>> tel

{'guido': 4127, 'irv': 4127, 'jack': 4098}

>>> list(tel.keys())

['irv', 'guido', 'jack']

>>> sorted(tel.keys())

['guido', 'irv', 'jack']

>>> 'guido' in tel

True

>>> 'jack' not in tel

False

2、The dict() constructor builds dictionaries directly from sequences of key-value pairs:

dict()构造器建立dictionaries从key-value配对的序列

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

{'sape': 4139, 'jack': 4098, 'guido': 4127}

3、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}

4、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}

Looping Techniques

1、When looping through dictionaries, the key and corresponding value can be retrieved at the same time using the items() method. 当循环通过dicitonaries,关键字和相应的值可以使用items()方法来获得。

>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}

>>> for k, v in knights.items():

...     print(k, v)

...

gallahad the pure

robin the brave

2、When looping through a sequence, the position index and corresponding value can be retrieved at the same time using the enumerate() function.  使用enumerate()函数来返回

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

...     print(i, v)

...

0 tic

1 tac

2 toe

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

使用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.

4、To loop over a sequence in reverse, first specify the sequence in a forward direction and then call the reversed() function.  使用reversed()函数,相反地去循环一个序列。

>>> for i in reversed(range(1, 10, 2)):

...     print(i)

...

9

7

5

3

1

5、To loop over a sequence in sorted order, use the sorted() function which returns a new sorted list while leaving the source unaltered.  按顺序sorted()

>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']

>>> for f in sorted(set(basket)):

...     print(f)

...

apple

banana

orange

pear

More on Conditions

The conditions used in while and if statements can contain any operators, not just comparisons.  while和if语句包含任何操作。但是不包含比较

The comparison operators in and not in check whether a value occurs (does not occur) in a sequence

in和not包含了比较是否出现

The operators is and is not compare whether two objects are really the same object

is和is not是否为同一个对象

2、Comparisons can be chained. For example, a < b == c tests whether a is less than b and moreover b equals c.

比较可以链接起来。a是否小于b并且b是否等于c

3、Comparisons may be combined using the Boolean operators and and or

比较可以使用布尔操作符and和or,not

between them, not has the highest priority and or the lowest, so that A and not B or C is equivalent to (A and (not B)) or C.   最高not,然后and,最后or

The Boolean operators and and or are so-called short-circuit operators

and和or操作符是短路操作符。

Comparing Sequences and Other Types

(1, 2, 3)              < (1, 2, 4)

[1, 2, 3]              < [1, 2, 4]

'ABC' < 'C' < 'Pascal' < 'Python'

(1, 2, 3, 4)           < (1, 2, 4)

(1, 2)                 < (1, 2, -1)

(1, 2, 3)             == (1.0, 2.0, 3.0)

(1, 2, ('aa', 'ab'))   < (1, 2, ('abc', 'a'), 4)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息