Python Note One
- Hexaadecimals and Octals
|
|
- Complex number arithmetic
|
|
#!/usr/bin/env python
Container consists of sequences and mappings
Python has six built-in types of sequence:
lists
,tuples
,unicode strings
,strings
,buffer objects
,xrange objects
extracting elements from right to left:
|
|
- convert between list and string
|
|
a.extend(b)
can be done bya[len(a):] = b
numbers.insert(3, 'four')
can be done innumbers[3:3]=['four']
pop
remove an element (by default the last one) from the list and return it.pop(0)
remove the firstremove
remove the first occurrence of a valuesorted(cmp, key=None, reverse=False)
Format specifier:
%
Conversion flags
-
left alignment+
a sign should precede the convered value.- `` a space should precede positive numbers
0
zero padded
Minimum field width: if
*
the width will be read from the value tuple.
followed by precisionConversion type:
- eg
x
hexadecimal '%x' % 42
=> 2a
- eg
Examples:
'%10f' % pi
=>3.141593
'%10.2f' % pi
=>3.14
'%.2f' %pi
=>3.14
'%.5s' % 'Ang Gao'
=>'Ang G'
'%.*s' % (5, 'Ang 'Gao')
=>'Ang G'
'%010.2f' % pi
=>0000003.14
'%-10.2f' % pi
=>3.14
String translate: only works with single character
|
|
optional second argument can be supplied to translate,
specifying letters that should be delete: text.translate(table, 'ab')
- String translate in PY3
|
|
String formatting with dict:
'%('))le)s' % {'title':'Ang'}
dict methods
- copy(): shallow copy
- deep copy:
from copy import deepcopy
dc = deepcopy(dit)
- fromkeys: create new dict with the given keys
{}.fromkeys(['name', 'age'])
dict.fromkeys(['name', 'age'])
dict.fromkeys(['name', 'age'], 'unknown')
- get: return None if key not exists or supply default value
names.get('name', 'default')
- pop(key): get value, remove key-value pair
- popitem(): pops off an arbitrary item (key, value)
- setdefault: similar to get retrieve a value associate with a key, sets the value corresponding to the given key if it is not in dict
In PY3:
a,b,*rest = [1,2,3,4]
chr(ord('a')) = 'a'
name = raw_input('Name ') or 'unknown'
assert expression [, msg]
else clauses in loop:
|
|
exec
VSeval
|
|
eval(raw_input(...))
has same effect as input(..)
callable(x)
in PY3hasattr(x, '__call__')
scoping
- vars()
- without argument =
locals()
- with argument =
object.__dict__
- without argument =
- globals(): a dict with the global vars
- vars()
change global var
|
|
A function that stores its enclosing scope is called a closure. Normally cannot rebind var in outter scope, in PY3 the keyword nonlocal is introduced. It is used in much the same way as global, and lets you assign vars in outter but none global scopes
map
,filter
,reduce
moved tofunctools
module