A EDITORIAL
without permission shall not be reproduced, thank you ~ ~
to Python should have more than a year's time, with the experience of C ++ has not seriously systematically studied Python directly to get started -
currently used is OK, but the overall feel is not enough, say Misfortune cut wood work, there was still necessary to re-learn about the system.
In this paper, this reference: Magnus Lie Hetland forward, Python and others based tutorial Secretary-dimensional translation. Here to be a major note-taking, and does not contain all the knowledge point oh, like the installation of python, so do not write addition and subtraction up waste everyone's time, of course, things are just too details need to use time to studying it.
chap 1 Basics
1.1 basis of numbers and expressions
Arithmetic expression
division:/
Divisible: //
Remainder:%
variable
python variables is very flexible;
the variable name may include letters, numbers, and underscores, but can not start with a number;
function
Built-in functions used for example: abs () pow () round ()
Module
Directly into the module import model, then calls the function model.function
directly introduced from the function model import function module
1.2 String
String representation
str (): the value into a string form reasonably
repr (): python in the form of a legal expression to represent the values;
data input
input (): Suppose the user input is a legitimate expression of the python;
raw_input (): all original input as an input;
Long string representation
With three marks' '' instead of regular marks;
or last character line is a backslash \
The original string
Wherein the escape character is ineffective, which is what is what;
original string beginning with R & lt;
chap2 lists and tuples
The main difference is that the list can be modified, but not ancestral;
sequence itself may also comprise other sequences;
2.1 General Operation Sequence
All sequences contain an index, fragmentation, addition, multiplication, check whether there is an element other operations.
In addition, further having computing Python sequence length, built-in functions to find the maximum and minimum elements.
index
String is a sequence of characters, as an example: greeting = 'Hello'
From the first index number 0, greeting [0] = 'H'
Negative index, starting from the last number -1, greeting [-1] = 'o'
Fragmentation
For accessing an element within a certain range;
by: two indexes spaced achieved;
Numbers = [0,1,2,3,4,5,6,7]
Numbers [. 3:. 6] = [3,4-, 5]
first index value comprises within the boundary, the second index value is not included within the boundaries ;;
Example: access the last three elements numbers [-3: -1] or directly numbers [-3:], the last a blank.
The above steps are the default setting of 1;
Display the steps: numbers [1: 6: 2 ] from 1 (included) to a sixth (not included) in each of the first two elements;
displays the negative steps: numbers [6: 1: -2 ] 6 from (including) number 1 to (not including) the first two elements each;
Sequences are added
+ Sequence may be directly summed;
but it must be the same types of transactions;
multiplication
'Hello' * =. 3 'hellohellohello'
[21 is] * =. 3 [21, 21,]
can be used to initialize the empty list: sequence = [None] * 10
Membership
Check whether the element included
in
the return at the True
False if not
Length, maximum and minimum values
python's built-in functions
len () number of elements contained in the sequence;
min () minimum sequence;
max () the maximum value of the sequence;
2.2 List: python's 'coolie'
Unlike the local list of tuples and strings: the list is variable.
list function
list () to create a list of a character string;
Example: List [ 'Hello'] = [ 'H', 'E', 'L', 'L', 'O'];
List of sequences for all types, not just strings;
The basic list operations
Normal operation of all sequences: the index, fragmentation, addition, multiplication, length list apply;
some of which may change the list of methods: element assignment element removal, slice assignment list method;
elements assigned: x [1] = 2
Delete assignment: del x [1]
Slice assignment: x [2:] = list ( 'hello')
A list of methods: Methods are functions that are closely associated with certain objects, invoke methods: Object methods ()
.append () need not be added at the end of the list of elements;
.count () count the number of times an element can occur;
.extend () can be extended with a new list of the original list;
.index () to find a value index position in the list of the first occurrence;
.insert () is inserted into the object list;
.pop () removes an element in the list (default is the last one), and returns the element values;
combination .append () and .pop () stack can be achieved.
.remove () removes the first occurrence of a value in the list.
.reserve () Reverse the elements of the list is stored.
.sort () to sort the list in its original location, the default from small to large. If you need to keep the original x, required by y = x [:] x value of the depth of the copy, and then sort the y. Note that y = x is of no use, a shallow copy.
2.3 yuan Zu: sequence immutable
If separated by commas some value, it automatically creates Ganso.
= 1,2,3 (1,2,3)
tuples are enclosed by parentheses.
Ganso empty :()
Only a neuron progenitor value: 42 = (42) there must be a comma
tuple function
Consistent with the list of the list functions.
The sequence as a parameter and converts it into tuples
tuple ([1,2,3]) = ( 1,2,3)
Basic Ganso Operation
Creating Ganso: x = 1,2,3
Access tuples: x [1]
Can substitute
In general, most of the things sequence by the list meet;
however Ganso can be used as keys in a map to use, but the list does not work;
Ganso as many built-in functions and methods return values exist, these times must be processed Ganso.
string chap3
3.1 Basic string operations
All standard operating sequence: the index, fragmentation, addition, multiplication, length, etc. of the maximum and minimum take strings applicable;
but the string is immutable.
3.2 Formatting string
% S formatted string
% F floating point formatted
% .3f to floating point format, and to three decimal places
% C formatted into a single character
% I formatted into a decimal integer with a sign
3.3 Method string
.find()
Find a long string substring, returns the substring of the location of the leftmost index;
if not then return -1;
The method may further specify the starting and ending range value is located;
join()
Is split () method of inverse;
queue element must be a string;
Example:
seq=[‘1’,‘2’,‘3’]
sep=’+’
sep.join(seq)
seq=‘1+2+3’
lower()
Returned lowercase version of the character string;
replace()
Alternatively arms return string matches a string obtained;
.replace ( 'waiting replace', 'latest replacement')
split()
join () method of the inverse, for dividing the character string into a sequence;
.split ( '') split with \ character boundaries.
strip()
Back removal sides (not including internal) spaces strings
can be removed at both ends of the specified character, .stripe ( 'ends to be removed')
Updated every day a little bit ~ ~ ~ ~
chap4 dictionary
Reference data structure value by name;
dictionary is built only python mapping type;
values in the dictionary is not particularly order, but are stored in a specific key in the key;
key may be a number, a string or even ancestral;
4.1 to create and use a dictionary
phonebook = { 'alice': ' 2341', 'beh': '9021'}
dictionary by a plurality of keys corresponding to a value of the composition formed
by each key and the corresponding values: spaced
between to use, separated open
the dictionary by a set of {} parentheses.
Empty dictionary: {}
The dictionary is the only key, but its value is not unique.
4.2 dict function
Such sequences may be mapped to other (such as other dictionaries) or (key, value) for the establishment of the dictionary.
example:
items=[(‘name’,‘alice’),(‘age’,12)]
d=dict(items)
print(d[‘name’])
‘alice’
4.3 The basic dictionary operations
many acts are similar to the sequence.
len (d) Returns the number of key-value;
D [k] is the key to return the value of k;
d [k] = v a d [k] assignment;
del d [k] is k the Delete key item;
k in d k check whether there is a key item;
4.4 dictionary method
.clear () clear all entries in the dictionary, and the place of operation, in-place operation;
.copy () is a shallow copy, the copy can be used DeepCopy () function to complete the deep copy;
.fromkeys () using the given key to create a new dictionary, each key corresponding to the default value none;
.get () when accessing the key does not exist by this method is not given, but will give a value of None;
.items () will return a list of all dictionaries embodiment, each item in the list items are derived from a (key, value);
.iteritems () Returns an iterator object rather than a list;
.keys () and .iterkeys () respectively dictionary mode key to return to the list, and returns an iterator for bonds;
.values () and .itervalues () are the values in the dictionary as a list returned, and the return value for the iterator;
.pop () Gets the value corresponding to the given key, and the key - the value of removing from the dictionary;
.popitem () pops up random items;
.Update () can use a dictionary updated by another dictionary entry;
chap5 conditions, loops, and other statements
for more information and import of 5.1 print
When used with a print, a plurality of expressions may be output
when the import can be introduced throughout the modules, one or more functions, can also act as an alias with a keyword;
5.2 Assignment of the many uses
Unpacking sequence
A plurality of assignment can be performed simultaneously: x, y, x = 1,2,3
Can be used to exchange two or more variables: x, y = y, x
When a function or method returns tuples, this feature will be particularly useful;
Chain assignment
Chain assignment is assigned the same value is assigned a shortcut plurality of variables;
X = Y = sonfunctions ()
Augmented assignment
X = x + 1 will be written as x + = 1
5.3 statement block: indent fun
python not represented} {C ++ like block of statements
are represented by statement blocks indented
5.4 Conditions and conditional statements
True and false judgment
The following values are false: False None 0 "" () [] {}
In addition to the above are true.
Conditional execution and if statements
if
elif
the else
if statements can be nested if statements inside
More complex conditions
y is equal to x == yx
xy x<=y x>=y
x! = yx not equal to y
x is yx and y is an object
x is not yx and y is not an object
x in yx y is a member of
x not in yx y is not a member of
compare strings alphabetically in the arrangement
and conditions are established
or have a condition established
Affirmation
assert statement into a checkpoint in the program, if the error interrupt the program and give tips;
5.5 cycle
Useful Expressions
while
for
can be used for as much as possible while not
Some iteration tool: zip parallel iterative
zip can be used for parallel iteration, the two sequences are compressed together, and then returns a list of tuples;
may be a plurality of sequences
may additionally be used sequences of unequal length, the shortest run stopped after
Example:
names=[‘alice’,‘ivy’]
ages=[‘12’,‘18’]
zip(names,ages)
for name, age in zip(names,ages):
print(name,age)
Some iteration tools: enumerate number of iterations
When you want to iterative sequence of objects, but also get the current index value of the object;
for example:
for index,string in enumerate(strings):
if xxx
in string:
strings[index]=‘new’
Some iteration tools: Flip and sorting iteration
reversed and inverted version of the return sorted or sorted;
Out of the loop
break out (end) cycle;
continue the loop out of the remaining end of the cycle but does not;
using a while loop ends embodiment according to the desired conditions;
5.6 List comprehensions
List list comprehension comprehension is using another list to create a new list of
embodiments: [x * x for x in range (10)]
例:[x*x for x in range(10) if x % 3==0]
例: [(x,y) for x in range(3) for y in range(3)]
Must be used [] brackets
5.7 Supplementary
pass do nothing, it is commonly used placeholder
We can also use del del delete a variable, but only delete the variable name itself, does not delete the actual value, python interpreter will make a direct garbage collection.
exec and eval are not very common;
chap 6 Abstract: Functions
That is how the statement is organized into function;
6.1 Creating function
def functionname (params) Create a function called functionname
increase notes to the function, in addition to using a #, may also be used within the function 'two single quotes written description of the function, which will be stored as part of the function , called the document string.
Call functionname .__ doc__ can access to the document string corresponding to the function;
6.2 function parameters
Common usage parameters is given in the order
or directly using the keywords given parameters, so that you can not control the order parameter
* Params all values can be placed in the same ancestral, these values will be collected and then used.
* The meaning is to collect the rest of the position parameter, if you do not provide any parameters for collection, params is an empty Ganso ()
** parmas to do is be able to handle the collection of keyword arguments, the keyword - value into the dictionary as a collection item.
Specific reference blog: collection parameter mechanism functions in Python
chap 7 more abstract: class
Object-oriented three characteristics: polymorphism, encapsulation, inheritance,
creating a new class: class className :, then used inside def keyword defined function;
Keyword self worth is a reference to the object itself, this point in the class is very useful;
self in fact is the difference of methods and functions
chap8 abnormal
python with the exception object to represent anomalies. After an error is encountered, an exception is thrown;
if not handled exception object or arrest, the program will use the so-called back (traceback) terminates execution;
8.1 Some built-in exceptions
Exception: the base class for all exceptions
AttributeError: When property reference or assignment failure caused
When you try to open a file that does not exist: IOError
When using an index does not exist in the sequence: IndexError
When using key mapping does not exist: KeyError
NameError: When can not find the name (variable)
SyntaxError: error code form;
TypeError: When the built-in function to the operation or of the wrong type
When the object is built-in operation or function to correct type, but the object using inappropriate value: ValueError
ZeroDivisionError: initiator except when the second parameter is 0 in the division operation or molded
8.2 custom exception class
The vast majority of cases have more than enough;
but when you need to customize, just their own Exception class can inherit;
class SomeCustomException (Exception): Pass
8.3 catch exceptions
With a try / except keywords to catch exceptions and make some processing
try: behind the need to check with unusual statement
except Exception: followed particular exception type want to capture, and the corresponding error processing
can have multiple except
Can then try / except later statements add else: clause
also the finally a: keyword for processing after the possible exception
Example:
try:
1/0
except NameError:
print (“unknow variable”)
else:
print (“that went well”)
finally:
print (“cleaning up”)
8.4 Abnormal function
An exception is thrown within a function without being processed, it will spread to the local function call;
if the treatment has not been invoked in place, it will continue to spread to the main program;
if the main program is not dealt with, it will terminate along a stack trace;
of course, some programs used if / else implement exception handling better than the try / except;
chap9 methods, properties, and the iterator
9.1 constructor
the init ()
When an object is created, it will call the constructor method immediately;
want to pass parameters to the constructor, when the class is initialized in time to pass parameters directly into the like;
General methods and specific override constructor
When a class (subclass) inherits a class (parent class, superclass) method which can be overridden;
will first search method in a subclass
can not find time to go to the parent class will find
it a subclass of default under no constructor initializes the parent class, then look at the 2,3 point can be solved;
Call the parent class constructor unbound
In simple terms, it is to increase the row of the female type. In the initial configuration of the subclass of the init (Self)
Use super function
Increase his super (parent class, self). In the initial configuration of the subclass in the init ()
9.2 Member access
The basic sequence and mapping rules
Sequence is a collection of objects and mapping.
If the object is not changed, then the use of the former two methods;
if the object variable, then use the four methods;
len (Self): This method should return the number of items included in the collection;
getItem (Self, Key): This method returns the value corresponding to the key;
setItem (Self, key, value): This method should be stored according to a certain value and the associated key, then this value may be acquired by __getitem__ method. Of course, this method also can be defined as an object that can be modified;
delItem (Self, Key): This method is called when the del statement on the part of the object, and must delete and elements related to the key. This method is also possible to modify the object defined above;
Subclass lists, dictionaries and strings
Way to achieve all of the above is needed is a massive undertaking, and it is difficult to do.
If you want custom behavior in one operation, while the other methods do not achieve: inheritance
is when you want to subclass a built-in type (example list), went to class inheritance list, and then override the method that is what you want can.
9.3 Properties
property function
It is possible to realize a method of encapsulating an attribute;
specific reference may be: to understand and use the in Python @property
Static methods and class member method
Static methods are methods and class members when creating an object is loaded and the type Staticmethod Classmethod types.
No self static method defined parameters, and the class itself may be invoked;
class members needed when defining a method called a self similar parameters cls class members method can be used with a particular class of objects directly call.
@ Can also be used in decorative lists above methods or functions, for example: @staticmethod @classmethod
9.4 iterator
Based approach __iter__ iterator rules
Iterator rules
__iter__ method returns an iterator
iterator refers to the object with the next method;
when you call the next method, the iterator will return to his next value.
In python0.3, the method is __next__
Sequence obtained from the iterator
Example:
class TestIterator:
value=0
def next(self):
self.value+=1
if self.value > 10 : raise StopIteration
return self.value
def iter(self):
return self
these TestIterator = ()
list (these)
[1,2,3,4,5,6,7,8,9,10]
__iter__ function returns itself
the Next (Self) placed you want him to do iterative
Builder 9.5
Generators and iterators is probably the most powerful of the two features introduced in recent years;
generator can help readers to write very elegant code;
Generator is a common syntax for defining a function with iterators;
Create a builder
Create a generator as simple as creating functions;
for example, take nested = [[1,2], [ 3,4], [5]] in order to print out, the solution is as follows:
def flatten(nested):
for sublist in nested:
for element in sublist:
yield element
Any function containing a yield statement is called a generator;
behavior generator and an ordinary function is very different. It's not like return as the return value, but each produces multiple values. Value generated each time a yield statement, the function will be frozen; that is, functions parked there waiting to be activated, the function is activated after started from that point stopped.
The next iteration may be used by all values in the generator;
for num in flatten(nested):
print num
or
list(flatten(nested))
Here it is more to being the first ~~~~~~~
hope that we can learn together hee hee