[原创] Learning in Python:Chapter 4 Introducing Python Object Types

Chapter 4: Introducing Python Object Types

 
 
1. Build-in Types:
 

        
 
2. Numbers:
  • Python support big numbers
  • Modules: math, random
3. String:
  • String is a Sequence
  • Sequence operation:
    • len(s)
    • s[1], s[-1]
    • s[1:3], s[:3], s[1:], s[:-1]
    • s + 'abc'
    • s*8
  • Type-Specific methods:
    • s.find('abc')
    • s.replace('abc','bbb')
    • s.split(',')
    • s.upper()
    • s.isalpha(), s.isdigit()
    • s.rstrip()
    • Formating:
      • '%s hello, %s world' % ('I', 'python')
      • '{0} hello, {1} world'.format('I','python')
      • '{0:o}, {1:x}, {2:b}'.format(64, 64, 64)
  • String is Immutable (not changing the original string, but creating new one), but can be used to make new strings.
  • numbers, strings, and tuples are immutable; lists and dictionaries are not
  • \0 does not teminates a string
  • """  """ for mutiple-line string. r'' for raw string
  • pattern matching:
    • module:  re
3. Getting help
  • dir(s), help(s.replace)
 
4. List
  • Mutable, Sequence
  • Tpye-Specific Operations:
    • L.append()
    • L.pop(2)    # pop out the second last item
    • L.insert()
    • L.remove()
    • L.sort()
    • L.reverse()
  • Comprehension:
    • [row[1] + 1 for row in M]
    • [row[1] + 1 for row in M if row[1]%2 == 0]
    • {ord(x) for x in 'spaam'}
    • {x:ord(x) for x in 'spaam'}
  • Generator
    • G = ( sum(row) for row in M )
    • next(G)
5. Dictinary
  • Mapping (no order), mutable
  • Type-specific operations:
    • D.keys()
    • sorted(D)  The Dictionary can be ordered.
  • Iteration Protocol: a physically stored sequence in memory.
  • Time optimization module: time,  timeit, profile
  • Missing Key:
    • if a in D
    • get: value = D.get('x', 0)
    • if/else expression: value = D['x'] if 'x' in D else 0
6. Tuples
  • A list that cannot be changed: immutable
  • Type-specific methods:
    • T.index(4)   return the index of 4
    • T.count(4)   return the exsit times of 4
7. Files
  • file = open("abc.txt","w")
    • w: clear/create a file for writing
  • file.write()
  • Read:
    • file.read(), read the entire file
    • file.readline(), read one line at a time
  • file.seek()
8.set
  • X = set('spam')
  • Y = {'h', 'a', 'm'}
  • >>> X, Y
  • >>> X & Y # Intersection
  • >>> X | Y # Union
  • >>> X – Y # Difference
  • >>> {x ** 2 for x in [1, 2, 3, 4]} # Set comprehensions in 3.0
9.  type build-in function
  • type()    return the type of a object
  • isinstance(L, list)
posted @ 2012-09-29 21:07  icemoon1987  阅读(241)  评论(0编辑  收藏  举报