python中常用的built-in函數


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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM