Skip to content

Instantly share code, notes, and snippets.

@rswofxd
Created June 10, 2012 09:15
Show Gist options
  • Save rswofxd/2904605 to your computer and use it in GitHub Desktop.
Save rswofxd/2904605 to your computer and use it in GitHub Desktop.
Python://CodeCut.py/生命很短暂,精简就是生命
#coding:utf-8
###########################################
#生命很短暂,精简就是生命
###########################################
#交换变量避免使用临时变量
#########################
#M1
temp = x
x = y
y = temp
#M2
u, v = v, u
#############################
#读字典时避免判断键值是否存在
#############################
#M1
if 'key' in d:
print(d['key'])
else:
print('not found')
#M2
print(d.get('key','not found'))
###########################
#寻找最小值和位置的代码优化
###########################
#M1
mval, mpos = MAX, 0
for i in xrange(len(s)):
if s[i] < mval: mval, mpos = s[i], i
#M2
mval,mpos = min([(s[i],i) for i in xrange(len(s))])
#########################
#文件读取工作的最简单表达
#########################
#M1
line = ''
fp = open('text.txt', 'r')
for line in fp: text += line
#M2
text = string.join([line for line in open('text.txt')], '']
#M3
text = ''.join([line for line in open('text.txt')])
#M4
text = file('text.txt').read()
#################
#Python实现三元式
#################
#M1
if n>=0:
print('positive')
else:
print('negitive')
#M2
print((n>=0) and 'positive' or 'negitive')
#M3
#'and'和'or'相当于'a?b:c'作用,
#表达式为真,'or'被短路,否则'and'被短路
print((n>=0 and ['positive'] or ['negitive'])[0])
#M4
#将两个值组装成元组,即使'positive'是None, '', 0 之类整句话都很安全
#(FalseValue, TrueValue)[Condition]是利用了元组访问 + True=1 两条原理
print(('negitive', 'positive')[n>=0])
###############################
#避免字典成员是复杂对象的初始化
###############################
#M1
if not y in d:
d[y] = {}
d[y][x] = 3
#M2
d.setdefault(y, {})[x] = 3
#M3
d.setdefault(key, []).append(val)
###############################################
#把文本的IP地址转化为整数
#类似'192.168.10.214'的IP地址转化为 0x0C0A80AD6
###############################################
f = lambda ip: sum([int(k)*v for k, v in zip(ip.split('.'), [1<<24, 65536, 256, 1])])
###############################
#输出一个对象各个成员的名称和值
###############################
g = lambda m: 'n'.join(['%s=%s'%(k, repr(v)) for k, v in m.__dict__.iteritems()])
print(g(x))
##############
#获取链表索引
##############
for (index, item) in enumerate(list):
print(index, item)
##########################
#尽可能地使用'in'操作符
#适用于dict,list,tuple,set
##########################
for key in d:
print(key)
#######################
#使用函数生成字符串列表
#######################
result = ''.join(fn(i) for i in items)
#######################
#结构化的数据上使用循环
#######################
people = [info, ['Guido', 'BDFL', 'unlisted']]
for (name, title, phone) in people:
print name, phone
######################
#Python中Switch-case语句实现
######################
def switchCase(type, *args):
message = { 'type1': lambda: func1(*args),
'type2': lambda: func2(*args),
}
return message[type]()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment