built-in 函数在 builtins
模块中,不需要导入,但可以将函数指向其它变量
import builtins builtins.xxx = xxxx
所有 bulit-in 函数在 https://docs.python.org/3/library/functions.html
reduce 函数在3.0被移至 functools,所有 functools 函数在 https://docs.python.org/3/library/functools.html
from functools import reduce
除去 bulit-in 和 functools,还有非常多函数 https://docs.python.org/3/library/index.html
all & any
all(iterable) def all(iterable): for element in iterable: if not element: return False return True any(iterable) def any(iterable): for element in iterable: if element: return True return False
输入一个可迭代对象,
如果对象 全是Ture 或 对象为 空,则 all 返回 True
如果对象存在 至少一个True,则 any 返回 True,但对象为 空 则返回 False
a = '' # True False b = '1' # True True c = [] # True False d = [0] # False False e = [0, 1] # False True f = [1, 2, None] # False True g = [1, 2, False] # False True for i in a, b, c, d, e, f, g: print(all(i)) ''' 结果: all any True False True True True False False False False True False True False True '''
complie
compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)
dir
dir([object])
官方文档
>>> import struct >>> dir() # show the names in the module namespace # doctest: +SKIP ['__builtins__', '__name__', 'struct'] >>> dir(struct) # show the names in the struct module # doctest: +SKIP ['Struct', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__initializing__', '__loader__', '__name__', '__package__', '_clearcache', 'calcsize', 'error', 'pack', 'pack_into', 'unpack', 'unpack_from'] >>> class Shape: ... def __dir__(self): ... return ['area', 'perimeter', 'location'] >>> s = Shape() >>> dir(s) ['area', 'location', 'perimeter']
divmod
divmod(a, b)
同时取整和取余
输入两个数,返回一个tuple,(a//b, a%b)
enumerate
enumerate(iterable, start=0)
枚举
官方文档
>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter'] >>> list(enumerate(seasons)) [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')] >>> list(enumerate(seasons, start=1)) [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')] # Equivalent to: def enumerate(sequence, start=0): n = start for elem in sequence: yield n, elem n += 1
# 可以顺序保存文件 for index, seq in enumerate(seqs): with open('%s.%s' % (index, seq.split('#')[0]), 'wb') as f: f.write(seq)
filter
filter(function, iterable) # 输入一个函数和一个可迭代对象,返回一个可迭代对象
filter 需要输入一个函数和一个可迭代对象,返回一个filter对象,为迭代器,因此可以用 list,tuple 接收
当函数的返回值为True时,传入的元素被保留,False则舍去
filter本意为过滤,因此可以直接从一个列表以某种形式得到符合条件的新列表,对删除比较好用,因为在for循环中不能直接删除原列表元素。
如:有一个序列列表,用filter可以查找含有某片段的序列
def find_seq(seq): try: seq.index('ccc') return True except: return None seq = ['actgatcgatcgatgtcccgtgtg', 2, 4, 5, 'cacacacgggtgttt', 9, 10, 'gtgacacatgggggg'] print(list(filter(find_seq, seq))) # 结果:['actgatcgatcgatgtcccgtgtg'] seq = ['actgatcgatcgatgtcccgtgtg', 'cacacacgggtgttt', 'gtgacacatgggggg'] def find_seq(seq): return 'ccc' in seq print(tuple(filter(find_seq, seq))) # 结果:('actgatcgatcgatgtcccgtgtg',) # filter 返回为可迭代对象 from collections import Iterable print(isinstance(filter(find_seq, seq), Iterable)) # 结果:True # 例中isinstance()也是一个built-in函数,用法为isinstance(object, classinfo)
iter
iter(object[, sentinel])
可以把一个对象变成迭代器
官方文档
with open('mydata.txt') as fp: for line in iter(fp.readline, ''): process_line(line)
生成迭代器之后可以用 next() 调用
map
map(function, iterable, ...)
输入一个函数和一个可迭代对象,返回为 可迭代对象中每个元素 被 函数处理之后 相同顺序的迭代器
# 结合上一例中 iter 用法 with open('D:\STU\sari\BL21-DE3\sequence.fasta') as fp: new_iterator = iter(fp.readline, '') map_result = map(lambda x: x.find('TTTT'), new_iterator) print(map_result) print(list(map_result)[:10]) # 结果: <map object at 0x0000029FF9118B00> [-1, 3, 35, -1, -1, 21, 32, -1, 53, -1]
reduce
functools.reduce(function, iterable[, initializer])
传入一个函数和一个可迭代对象,返回值为将可迭代对象前两个元素用输入的函数处理,之后从第三个元素开始每次取一个和上一个结果传入函数
# 官方文档,reduce与下函数相同 def reduce(function, iterable, initializer=None): it = iter(iterable) if initializer is None: value = next(it) else: value = initializer for element in it: value = function(value, element) return value
# 也许可以用于一键合并字符串 from functools import reduce seq = ['actg', 'atcg'] print(reduce(lambda x, y: x+y, seq)) # 结果: actgatcg
reversed
reversed(seq)
# 与 reverse 对比 a = [1, 2, 3, 4, 5] a.reverse() # 此时 a = [5, 4, 3, 2, 1] print(a) b = reversed(a) print(b) print(list(b)) # 结果: [5, 4, 3, 2, 1] <list_reverseiterator object at 0x000001C69486F940> [1, 2, 3, 4, 5]
在字符串中,不可以使用 str.reverse() , 但可以使用 reversed(str), 同样返回一个迭代器,但用 list 接收时每个字符被分为一个元素
round
round(number[, ndigits])
保留小数
import numpy as np print(round(np.pi, 3)) 结果: 3.142
slice
class slice(start, stop[, step])
产生的是一个 slice 类,使用时也是中括号
slice_1 = slice(1, 6 ,2) print(slice_1) print(list(range(10))[slice_1]) # 结果: slice(1, 6, 2) [1, 3, 5]
sorted
sorted(iterable, *, key=None, reverse=False)
输入一个可迭代对象,同时可选输入 key=函数名,reverse=T/F
默认为将输入对象按 ascii 排序,输入一个函数则将每个元素经过函数处理后再排序(如
key=str.lower ,
输出还是原对象中的元素,而不是小写),reverse为True则反序
不管输入 str 或 tuple 都是返回一个 list
int 和 str 不可以比较
zip
zip(*iterables)
官方文档
# Equivalent to: def zip(*iterables): # zip('ABCD', 'xy') --> Ax By sentinel = object() iterators = [iter(it) for it in iterables] while iterators: result = [] for it in iterators: elem = next(it, sentinel) if elem is sentinel: return result.append(elem) yield tuple(result)
x = [1, 2, 3] y = [4, 5, 6] zipped = zip(x, y) print(zipped) print(list(zipped)) x2, y2 = zip(*zip(x, y)) print(list(x2), y2) print(x == list(x2) and y == list(y2)) # 结果: <zip object at 0x000002CC61433BC8> [(1, 4), (2, 5), (3, 6)] [1, 2, 3] (4, 5, 6) True
bin & oct & hex
bin(x)
oct(x)
hex(x)
分别为 2进制,8进制,16进制
chr & ord
chr(i)
ord(c)
chr 输入一个 int,输出对应的 Unicode 字符
ord 输入一个 字符,输出对应的 Unicode int