1. Dictionary
Mapping operations:
d['quantity']+=1
Create a dictionary:
d={}
d['name']='bob'
d['job']='dev'
d['age']=40
Nesting:
d={'name':{'first':'Bob','last':'Smith'},'job':['dev','mgr'],'age':40.5}
res['name']['first'] is the 'Bob'
We can not sort the dictionaries directly, but we can sort the keys.
ks=d.keys()
ks.sort()
for key in ks: print key, '=>', D[key]
Another way is:
for key in sorted(D): print key, '=>', D[key]
2. Iteration
squares=[x**2 for x in [1,2,3]] #result is [1,4,9]
3. Performance
using time and timeit modules and the profile module to find more information about the code.
4. Check missing keys
We can add new keys to dictionaries, but fetching nonexistent keys are still a mistake.
d.has_key('f')
if not d.has_key('f'): print 'missing'
5. Tuples
t=(1,2,3)
tuples are similar to list, but they are immutable, they cannot be changed in place.
6. Files - core type of python
f=open('data.txt','w')
f.write('Hello\n')
f.close()
read mode is the default one.
f=open('data.txt')
bytes=f.read() #read entire file into a string, here bytes is 'Hello\n', noticing the control characters
7. Set
X=set('spam') #result set(['s','p','a','m'])
Y=set(['h','a','m'])
X&Y #intersection
X|Y #union
X-Y #difference
8. Decimal
9. check the type
if type(L)==type([]): print 'list'
if type(L)==list: print 'list'
if isinstance(L,list): print 'list'
10. string format of numeric data
num=1/3.0
"%e" % num #result '3.3333e-001'
"%2.2f" % num #result '0.33'
Mapping operations:
d['quantity']+=1
Create a dictionary:
d={}
d['name']='bob'
d['job']='dev'
d['age']=40
Nesting:
d={'name':{'first':'Bob','last':'Smith'},'job':['dev','mgr'],'age':40.5}
res['name']['first'] is the 'Bob'
We can not sort the dictionaries directly, but we can sort the keys.
ks=d.keys()
ks.sort()
for key in ks: print key, '=>', D[key]
Another way is:
for key in sorted(D): print key, '=>', D[key]
2. Iteration
squares=[x**2 for x in [1,2,3]] #result is [1,4,9]
3. Performance
using time and timeit modules and the profile module to find more information about the code.
4. Check missing keys
We can add new keys to dictionaries, but fetching nonexistent keys are still a mistake.
d.has_key('f')
if not d.has_key('f'): print 'missing'
5. Tuples
t=(1,2,3)
tuples are similar to list, but they are immutable, they cannot be changed in place.
6. Files - core type of python
f=open('data.txt','w')
f.write('Hello\n')
f.close()
read mode is the default one.
f=open('data.txt')
bytes=f.read() #read entire file into a string, here bytes is 'Hello\n', noticing the control characters
7. Set
X=set('spam') #result set(['s','p','a','m'])
Y=set(['h','a','m'])
X&Y #intersection
X|Y #union
X-Y #difference
8. Decimal
9. check the type
if type(L)==type([]): print 'list'
if type(L)==list: print 'list'
if isinstance(L,list): print 'list'
10. string format of numeric data
num=1/3.0
"%e" % num #result '3.3333e-001'
"%2.2f" % num #result '0.33'
No comments:
Post a Comment