Thursday, October 3, 2013

Learning Python -- Part two

1. Dictionary

    dic = {'lilei':90,'lily':100,'sam':57, ''tom" :90}
   
    for key in dic
        print dic[key]

    print dic.keys(),  return all keys
            dic.values(), return all values
            dic.items(),  return all element
            dic.clear(),  clear dic, dic become {}

   del dic['tom']  , delete 'tom' in dic, del is the keyword
   
2. file
   
    f = open(filename, mode), "r" read, "w" write
    content  = f.read(N) , read N bytes data
    content  = f.readline(), read one line
    content = f.readlines(), read all the lines

    f.write('I like apple'), write to file

    f.close()

3. range(), enumerate(), zip()
    S = 'abcdefghijk'
    for i in range(0,len(S),2):
        print S[i]
 
    for (index,char) in enumerate(S):
        print index
        print char
 
    ta =[1,2,3]
    tb = [9,8,7]
    tc = ['a','b','c']
    for (a,b,c) in zip(ta,tb,tc)
        print(a,b,c)

    ta = [1,2,3]
    tb = [9,8,7]
    zipped = zip(ta,tb)
    print(zipped)

    na,nb = zip(*zipped)
    print(na,nb)


4. lambda
    func = lambda x,y: x+ y
    print func(3,4)

    def teset(f,a,b):
        print 'test'
        print f(a,b)
   test(func,3,5)

   test((lambda x: x+3),[1,3,5,6])

5. map
    re = map((lambda x,y: x+y),[1,2,3],[6,7,9])

6. filter
    def func(a)
        if a> 100:
            return True
        else:
            return False

   print filter(func,[10,56,101,500])

7. reduce
    print reduce((lambda x,y: x+y),[1,2,5,7,9])

8.  debug
     re = iter(range(5))

     try:
         for i in range(100):
             print re.next()
     except StopIteration:
         print 'Here is end ',i
    print 'HaHaHa'


    try:
        ...
    except error1:
        ...
    except error2:
        ...
    else:
        ...
    finally:
        ...

No comments:

Post a Comment