您的位置:首页 > 编程语言 > Python开发

Python Cookbook 学习笔记 可以拿来和面试官吹牛用

2011-08-03 22:42 597 查看
仅仅是Python Cookbook的代码而已,自己在看这书中觉得感兴趣的代码。

可以直接保存为py文件运行

# -*- coding: utf-8 -*-
#coding=utf-8
#################################################
print "复制一个对象副本"
import copy
a = [1, 2, 3, 4, 5, 6]
b = copy.copy(a)
###################################################
print "若列表中元素存在则返回之"
def list_get(L, i, v=None):
if - len(L) <= i < len(L):
return L[i]
else:
return v
#print "Input a List\n"
#L = raw_input('>')
#L = L.split(',')
#print "Input a Index\n"
#i = raw_input('>')
#i = int(i)
#a = list_get(L, i)
#print "a is %s" % a
#print "Bye"
####################################################
print "循环访问序列中的索引和元素"
def change_item(L):
'''L is a list'''
for index, item in enumerate(L):
print index,item
if item > 23:
L[index] = item - 1
change_item(a)
######################################################
print "创建一个10 x 5阵列"
multilist = [[0 for col in range(5)] for row in range(10)]
print multilist
for row in range(10):
for col in range(5):
print "8", #加个逗号,就可以不换行

print
#####################################################
'''
x=[1,2,3],y=['a','b','c']
zip(x,y)
[(1,'a'),(2,'b'),(3,'c')]
zip函数接受任意多个序列作为参数,将所有序列按相同的索引组合成一个元素是各个序列合并成的tuple的新序列,
新的序列的长度以参数中最短的序列为准。
另外(*)操作符与zip函数配合可以实现与zip相反的功能,即将合并的序列拆成多个tuple
zip(*zip(x,y))
[(1,2,3),('a','b','c')]

'''

print "二维阵列变换"
array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print map(list, zip(*array)),array #
#####################################################
print '从字典中取值'
a = {"b":2, "c":3, "d":4, "e":5}
print a.get('c')
print a.get("bc", "kk is a genius")
######################################################
print '在无需多引援的情况下创建字典'
data = dict(red=1, green=2, yellow=3)
print data
#######################################################
print "获取字典的一个子集"
d = {'a': 5, 'b': 6, 'c': 7}
def sub_dict(somedict, somekeys, default=None):
return dict([ (k, somedict.get(k, default)) for k in somekeys ])
def sub_dict_remove(somedict, somekeys, default=None):
return dict([ (k, somedict.pop(k, default)) for k in somekeys ])

def sub_dict_strict(somedict, somekeys):
return dict([ (k, somedict[k]) for k in somekeys ])

def sub_dict_remove_strict(somedict, somekeys):
return dict([(k,somedict.pop(k)) for k in somekeys])

def sub_dict_select(somedict, somekeys):
return dict([ (k, somedict[k]) for k in somekeys if k in somedict])
def sub_dict_remove_select(somedict, somekeys):
return dict([ (k, somedict.pop(k)) for k in somekeys if k in somedict])

print sub_dict(d, 'ab'), d
print sub_dict_remove(d, 'ab'), d

#print sub_dict_strict(d, 'ab'), d
#print sub_dict_remove_strict(d,'ab'),d

###########################################################
print "反转键值"
e = {'a': 5, 'b': 6, 'c': 7}
def invert_dict(e):
return dict([ (v, k) for k, v in e.iteritems() ])

from itertools import izip
def invert_dict_fast(e):
return dict(izip(e.itervalues(), e.iterkeys()))
print "e is", e
print invert_dict(e), e
###########################################################
print "设置默认值,setdefault 有key,返回值,若无新加【】"
key = 'black'
value = 1
d1 = { }
d.setdefault(key, [ ]).append(value)

#############################################################
print "在保留序列顺序的前提下,消除其中的重复"
test=[3,3,3,3,2,1,1,1,5,5,4,4,5,5]
def uniquer(seq, f=None):
#import pdb;pdb.set_trace()
""" Keeps earliest occurring item of each f-defined equivalence class """
if f is None: # f's default is the identity function f(x) -> x
def f(x): return x
already_seen = set( )
result = []
for item in seq:
marker = f(item)
if marker not in already_seen:
already_seen.add(marker)
result.append(item)
return result
print uniquer(test)
################################################################
print "记录异常信息except,写入字典"
'''
import cStringIO, traceback
def process_all_files(all_filenames, fatal_exceptions=(KeyboardInterrupt, MemoryError)):
bad_filenames = {}
for one_filename in all_filenames:
try:
process_one_file(one_filename):
except fatal_exceptions:
raise
except Exception:
f = cStringIO.StringIO()
traceback.print_exc(file=f)
bad_filenames[one_filename] = f.getvalue()
return bad_filenames
'''
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息