导航

Python基础教程——10 充电时刻

Posted on 2012-08-14 01:02  immiki  阅读(267)  评论(0编辑  收藏  举报

1 math和cmath模块分别包含了计算实数和复数的数学函数

2 任何Python程序都可以作为模块导入。windows为例 C:\python 目录下的hello.py文件

import sys

sys.path.append('C:/python')

import hello

在导入模块时代码将被执行,第二次导入则不再执行——导入模块主要用于定义

__name__ 在主程序中,值为'__main__',在导入的模块中,这个值就是模块名,例如hello2

#hello.py
def hello():
    print 'Hello,world!'
def test():
    hello()


if __name__ == '__main__' : test()


>>> import sys
>>> sys.path.append('C:/Python25/')
>>> import hello
>>> hello.hello()

Hello,world!

>>> hello.test()
Hello,world!

3 将模块放在合适的位置中,实现sys.path本身就含有正确的目录,如下: 或者修改环境变量PYTHONPATH

>>> import sys,pprint
>>> pprint.pprint(sys.path)
['F:/Python',
 'C:\\Python25\\Lib\\idlelib',
 'C:\\Windows\\system32\\python25.zip',
 'C:\\Python25\\DLLs',
 'C:\\Python25\\lib',
 'C:\\Python25\\lib\\plat-win',
 'C:\\Python25\\lib\\lib-tk',
 'C:\\Python25',
 'C:\\Python25\\lib\\site-packages',
 'C:/Python25/']  

其实,site-packages是专门用来放置用户自定义的模块的。

4 import 模块名

  dir(模块名) 查看模块中的内容,他会将对象以及模块的所有函数、类、变量等的所有特性列出来

  __all__ 定义模块的公有接口,没有的话,import *语句默认将会输出模块中所有不以下划线开头的全局名称

5

                         win      (unix和mac os x)   mac os

os.sep                \\                     /                       :

os.pathsep         ;                      :                       ::

os.linesep          \r\n                  \n换行符           \r单个回车符

 

6 为文件编写行号

#numberline.py

import fileinput

for line in fileinput.input(inplace = True):
    line = line.rstrip()
    num = fileinput.lineno()
    print '%-40s #%2i' %(line,num)
   

多次运行,每行将添加多个行号

7 集合

>>> set(range(10))
set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> a = set([1,2,3])
>>> b = set([2,3,4])
>>> a.union(b)
set([1, 2, 3, 4])
>>> a
set([1, 2, 3])
>>> a|b
set([1, 2, 3, 4])
>>> a
set([1, 2, 3])
>>> b
set([2, 3, 4])
>>> c = a&b
>>> c
set([2, 3])
>>> a
set([1, 2, 3])
>>> b
set([2, 3, 4])
>>> c.issubset(b)
True
>>> c <= a
True
>>> c<=b
True
>>> b<=a
False
>>> a.issuperset(c)
True
>>> a.issuperset(a)
True

 

示例 打印并集与reduce函数结合

 

>>> myset = []
>>> for i in range(10):
 myset.append(set(range(i,i+5)))

>>> myset
[set([0, 1, 2, 3, 4]), set([1, 2, 3, 4, 5]), set([2, 3, 4, 5, 6]), set([3, 4, 5, 6, 7]), set([8, 4, 5, 6, 7]), set([8, 9, 5, 6, 7]), set([8, 9, 10, 6, 7]), set([8, 9, 10, 11, 7]), set([8, 9, 10, 11, 12]), set([9, 10, 11, 12, 13])]
>>> reduce(set.union,myset)
set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13])

 

关于frozenset函数

 

>>> a = set()
>>> b = set()
>>> a.add(b)

Traceback (most recent call last):
  File "<pyshell#85>", line 1, in <module>
    a.add(b)
TypeError: set objects are unhashable
>>> a.add(frozenset(b))
>>> a
set([frozenset([])])
>>> b
set([])
>>> a.add(b)

Traceback (most recent call last):
  File "<pyshell#89>", line 1, in <module>
    a.add(b)
TypeError: set objects are unhashable

 ==================================================================

1 random模块使用示例P187

#pocker.py

values = range(1,11) + 'Jack Queen King'.split()
suits = 'diamonds clubs hearts spades'.split()
deck = ['%s of %s' %(v,s) for v in values for s in suits]
from pprint import pprint
#输出原始的前12张
pprint(deck[:12])
from random import shuffle
shuffle(deck)
#输出打乱后的前12张
pprint(deck[:12])
#每次回车发一张牌,直到所有牌都发完
while deck:

    raw_input(deck.pop())

2 P189 简单的数据库应用程序

#简单的数据库应用程序
#database.py
import sys, shelve
def store_person(db):
    """
    Query user for data and store it in the shelf object
    """


    pid = raw_input('Enter unique ID number: ')
    person = {}
    person['name'] = raw_input('Enter name: ')
    person['age'] = raw_input('Enter age: ')
    person['phone'] = raw_input('Enter phone number: ')


    db[pid] = person


def lookup(db):
    """
    Query user for ID and desired field, and fetch the corresponding data
    from the shelf object
    """


    pid = raw_input('Enter ID number: ')
    field = raw_input('What would you like to know? (name,age,phone) ')
    field = field.strip().lower()
    print field.capitalize() + ':',\
          db[pid][field]


def print_help():
    print 'The available commands are:'
    print 'store  : Stores information about a person'
    print 'lookup : Looks up a person from ID number'
    print 'quit   : Save changes and exit'
    print '?      : Prints this message'


def enter_command():
    cmd = raw_input('Enter command(? for help)')
    cmd = cmd.strip().lower()
    return cmd


def main():
    database = shelve.open('F:\\database.dat')
    try:
        while True:
            cmd = enter_command()
            if cmd == 'store':
                store_person(database)
            elif cmd == 'lookup':
                lookup(database)
            elif cmd == '?':
                print_help()
            elif cmd == 'quit':
                return
    finally:
         database.close()
if __name__ == '__main__': main()

运行示例

>>> 
Enter command(? for help)?
The available commands are:
store  : Stores information about a person
lookup : Looks up a person from ID number
quit   : Save changes and exit
?      : Prints this message
Enter command(? for help)store
Enter unique ID number: 001
Enter name: Jim
Enter age: 10
Enter phone number: 19-221
Enter command(? for help)lookup
Enter ID number: 001
What would you like to know? (name,age,phone) name
Name: Jim
Enter command(? for help)lookup
Enter ID number: 001
What would you like to know? (name,age,phone) phone
Phone: 19-221
Enter command(? for help)quit