python 有用的Python代码片段
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 有用的Python代码片段相关的知识,希望对你有一定的参考价值。
# 获取文件扩展名(e.g. .exe .txt)
extension = os.path.splitex(filename)[1]
# lazy property
# 惰性属性装饰器,第一次使用求值,之后使用直接从object.__dict__中取属性
class lazy_property(object):
def __init__(self, func):
self.func = func
def __get__(self, instance, cls):
val = self.func(instance)
setattr(instance, self.func.__name__, val)
return val
# key,value互换
>>> m = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
>>> {v: k for k, v in m.items()}
{1: 'a', 2: 'b', 3: 'c', 4: 'd'}
# list 分组
>>> a=[1,2,3,4,5,6,7,8,9,0]
>>> [a[i:i+3] for i in range(0,len(a),3)]
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [0]]
# 矩阵转置
>>> a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> print([[row[col] for row in a] for col in range(len(a[0]))])
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
>>> list(zip(*a))[:] # zip(*a) 即可 不过返回的是迭代器,而且内部是元祖
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
>>> list(map(list,zip(*a)))[:] # 通过map将tuple转换为list,map返回的也是迭代器
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
# namedtuple 简单的结构体
>>> from collections import namedtuple
>>> Point = namedtuple('Point', ['x', 'y'])
>>> Point.__doc__ # docstring for the new class
'Point(x, y)'
>>> p = Point(11, y=22) # instantiate with positional args or keywords
>>> p[0] + p[1] # indexable like a plain tuple
33
>>> x, y = p # unpack like a regular tuple
>>> x, y
(11, 22)
>>> p.x + p.y # fields also accessable by name
33
>>> d = p._asdict() # convert to a dictionary
>>> d['x']
11
>>> Point(**d) # convert from a dictionary
Point(x=11, y=22)
>>> p._replace(x=100) # _replace() is like str.replace() but targets named fields
Point(x=100, y=22)
# defaultdict
# 假设我们的字典中的value是一个list。我们要先判断key是否已经存在,如果不存在,则新建一个list并赋值给key,
# 如果已经存在,则调用list的append方法,将值添加进去。
d = {}
for key, value in pairs:
if key not in d:
d[key] = []
d[key].append(value)
d = defaultdict(list) # 这个方法更好
for key, value in pairs:
d[key].append(value)
# 字典的get方法
# 如果元素在字典中没有找到的话,则设为指定值
grade = record['Tom']
if grade is None:
grade =0
grade=record.get('Tom',0)
# 列表每个元素乘以一个值
l = [1, 2, 3, 4, 5]
l = [x * 2 for x in l]
# 复制列表
> a=[1,2,3]
> b=list(a)
> b=a[:]
# a or b
a = b if a is None else a
a= a or b # or 会在求得一个真值的时候返回
# 类型检查装饰器
def accepts(*types):
def check_accepts(f):
assert len(types) == f.func_code.co_argcount
def new_f(*args, **kwds):
for (a, t) in zip(args, types):
assert isinstance(a, t), \
"arg %r does not match %s" % (a,t)
return f(*args, **kwds)
new_f.func_name = f.func_name
return new_f
return check_accepts
Usage:
@accepts(int, (int,float))
def func(arg1, arg2):
return arg1 * arg2
func(3, 2) # -> 6
func('3', 2) # -> AssertionError: arg '3' does not match <type 'int'>
以上是关于python 有用的Python代码片段的主要内容,如果未能解决你的问题,请参考以下文章