To re-learn Python:
After learning a little python two years ago, I've never done anything about it, and basically forgot all about it.
or |
&
Ord () ASCII to 16 binary
Chr () 16 binary to ASCII
>>> u ' abc '. Encode (' utf-8 ') ' abc ' >>> u ' Chinese '. Encode (' utf-8 ') ' \xe4\xb8\xad\xe6\x96\x87 '
>>> ' abc '. Decode (' Utf-8 ') u ' abc ' >>> ' \xe4\xb8\xad\xe6\x96\x87 '. Decode (' Utf-8 ') u ' \u4e2d\u6587 ' >>> print ' \xe4\xb8\xad\xe6\x96\x87 '. Decode (' Utf-8 ') Chinese
Array list:
append(‘a‘) 插到后面
insert(1,‘a‘) 指定位置
Pop () Delete end Delete specified
Tuple tuples:
A tuple of only 1 elements must be defined with a comma ,
to disambiguate:
>>> T = (1,) >>> T (1,)
"Variable" tuple:
t = (‘a‘, ‘b‘, [‘A‘, ‘B‘])
Dict:key-value storage Mode
By in
Judging if key exists:
Iteritems
>>> ' Thomas ' in Dfalse
The Get method provided through Dict: If key does not exist, you can return none, or the value you specified (do not change dict)
Dict = { ' a ': "This A", ' B ': "This B", ' C ': "This C", ' d ': "This D"}print dict.get (' F ', "Hello") print D Icthello{' A ': ' This a ', ' C ': ' This C ', ' B ': ' This b ', ' d ': ' This d '}
pop(key)
the corresponding value is also removed from the Dict.
Compared with list, Dict has the following features:
- The speed of finding and inserting is very fast and will not increase with the increase of key;
- It takes a lot of memory, and it wastes a lot of memory.
And the list is the opposite:
- The time to find and insert increases as the element increases;
- Small footprint, Little wasted memory
Set: A set of keys, but no value is stored. Because key cannot be duplicated, there is no duplicate key in set.
You can add(key)
add elements to a set by means of a method, but you can add them repeatedly, but it won't work.
remove(key)
You can delete an element by means of:
>>> S1 = set ([1, 2, 3]) >>> s2 = Set ([2, 3, 4]) >>> S1 & S2set ([2, 3]) >>> S1 | S2set ([1, 2, 3, 4])
on non-mutable objects we have said that Str is an immutable object, and list is a mutable object. For mutable objects, such as list, to manipulate the list, the contents of the list will change, such as:>>> a = ['C','b','a']>>>A.sort ()>>>a['a','b','C'] and for non-mutable objects, such as STR, to operate on STR:>>> A ='ABC'>>> A.replace ('a','A')'ABC'>>>a'ABC'Although the string has a replace () method, it does change the'ABC', but variable a finally remains'ABC', how should we understand it? Let's start by changing the code to the following:>>> A ='ABC'>>> B = A.replace ('a','A')>>>b'ABC'>>>a'ABC'always keep in mind that a is a variable, and'ABC'is the string Object! In some cases, we often say that the content of object A is'ABC', but in fact, a is a variable, it points to the content of the object is'ABC':
Calling functions
Http://docs.python.org/2/library/functions.html#abs
How can I tell if an object is an iterative object? The method is judged by the iterable type of the collections module:
>>> from Collections Import iterable>>> isinstance (' abc ', iterable) # Whether STR can iterate true>>> Isinstance ([i], iterable) # Whether the list can iterate true>>> isinstance (123, iterable) # integer can be iterated false
Python's built-in enumerate
functions can turn a list into an index-element pair
>>> for I, value in enumerate ([' A ', ' B ', ' C ']): ... Print I, Value ... 0 A1 B2 C
>>> for x, y in [(1, 1), (2, 4), (3, 9)]: ... Print x, y ... 1 12 43 9
for
Loops can actually use two or more variables at the same time, such as dict
the iteritems()
ability to iterate key and value at the same time
>>> d = {' X ': ' A ', ' y ': ' B ', ' z ': ' C '}>>> for K, V in D.iteritems (): ... Print k, ' = ', v ... y = Bx = Az = C
List generation You can use a single line of statements instead of looping to generate the above list:
>>> [x * x for x in range (1, 11)][1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
>>> [x * x for x in range(1, 11) if x % 2 == 0][4, 16, 36, 64, 100]
>>> [m + n for m in ‘ABC‘ for n in ‘XYZ‘][‘AX‘, ‘AY‘, ‘AZ‘, ‘BX‘, ‘BY‘, ‘BZ‘, ‘CX‘, ‘CY‘, ‘CZ‘]
>>> import os # Import OS module, the concept of module is >>> [d for d in Os.listdir (# Os.listdir can list files and directories [ ' ADLM ', ' applications ', ' Desktop ', ' Library ', ' Movies ', ' Music ', ' Pictures ', ' public ', ' VirtualBox VMs ', ' Workspace ', ' XCode ']
All the strings in the list become lowercase:
List.lower()
>>> L = [' Hello ', ' World ', ' IBM ', ' Apple ']>>> [S.lower () for S-l][' hello ', ' World ', ' IBM ', ' Apple ']
Use the built-in isinstance
function to determine if a variable is a string:
>>> x = ' abc ' >>> y = 123>>> isinstance (x, str) true>>> isinstance (y, str) False
Generator generator: As soon as you change a list-generated form []
()
, you create a generator:
g = (x * x for x in range (10))
With G. next
() Print
The correct approach is to use for
loops, because generator is also an iterative object
>>> g = (x * x for x in range) >>> for n in G: ... Print N ... 0149
print b
change yield b
it to become a generator generator:
def fib (max): N, a, b = 0, 0, 1 while n < max: yield b # print b
A, B = B, a + b n = n + 1
Map ()
>>> def f (x): ... return x * x...>>> map (f, [1, 2, 3, 4, 5, 6, 7, 8, 9]) [1, 4, 9, 16, 25, 36, 49, 64, 81]
Reduce (f, [X1, x2, X3, x4]) = f (f (f (x1, x2), x3), x4)
>>> def add (x, y): ... return x + y...>>> reduce (add, [1, 3, 5, 7, 9]) 25
Upper ()--All letters capitalized
Lower ()--All letters lowercase
Capitalize ()--capital letters, other lowercase letters
Title ()--all words capitalized, other lowercase
filter()
The incoming function is applied to each element sequentially, and then True
False
the element is persisted or discarded depending on whether the return value is
def is_odd (n): return n% 2 = = 1filter (is_odd, [1, 2, 4, 5, 6, 9, 10, 15]) # results: [1, 5, 9, 15]
Python's built-in sorted()
functions can sort the list:
It can also receive a comparison function to implement a custom sort. For example, if you want to sort in reverse order, we can customize a reversed_cmp
function:
def reversed_cmp (x, y): if x > y: return-1 if x < y: return 1 return 0
By passing in a custom comparison function reversed_cmp
, you can sort in reverse order:
>>> Sorted ([36, 21, 12, 9, 5], reversed_cmp) [[5, 9]
Ignoring the case to compare two strings is actually the first to capitalize the strings (or all lowercase) before comparing them.
One thing to keep in mind when returning closures is that the return function does not refer to any loop variables, or to subsequent variables that change.
Closures note that the returned function references the local variable args within its definition, so when a function returns a function, its internal local variables are referenced by the new function, so it is not easy to implement them in a simple package. Another problem to be aware of is that the returned function is not executed immediately, but not until F () is called. Let's look at an example: Def count (): fs = [] for I in range (1, 4): def f (): return i*i fs.append (f) return FSF1 , F2, F3 = count () in the above example, each loop creates a new function, and then returns the 3 functions that were created. You might think that calling F1 (), F2 (), and F3 () results should be 1,4,9, but the actual result is:>>> F1 () 9>>> F2 () 9>>> F3 () 9
The anonymous function lambda x: x * x
is actually:
def f(x): return x * x
装饰器:
def log (func): def wrapper (*args, **kw): print ' call%s (): '% func.__name__ return func (*args, **kw) Return wrapper
@logdef now(): print ‘2013-12-25
now()
Put @log
to now()
the definition of the function, the equivalent of executing a statement:now = log(now)
偏函数
Import functoolsdef func (x, y): Print X+yfunc2 = Functools.partial (func, y= ' fuck ') func2 ("Hello")
模块别名:
Try: Import Cstringio as stringioexcept importerror: # Importing failed to capture Importerror import Stringio
Re-learning the Python series (i)? WTF?