您將4個不同“數字”的字符串解釋為數字,因此以4為基數.如果您有一串實際數字,范圍為0-3,則可以讓int()真正快速地生成一個整數.
def seq_to_int(seq, _m=str.maketrans('ACGT', '0123')):
return int(seq.translate(_m), 4)
python將字符串類型轉換為數字。上面的函數使用str.translate()用匹配的數字替換4個字符中的每個字符(我使用靜態str.maketrans() function創建轉換表).然后將所得的數字字符串解釋為以4為底的整數.
請注意,這將生成一個整數對象,而不是零和一個字符的二進制字符串:
>>> seq_to_int('TGTGAGAAGCACCATAAAAGGCGTTGTG')
67026852874722286
python將空值替換成0?>>> format(seq_to_int('TGTGAGAAGCACCATAAAAGGCGTTGTG'), '016x')
'00ee20914c029bee'
>>> format(seq_to_int('TGTGAGAAGCACCATAAAAGGCGTTGTG'), '064b')
'0000000011101110001000001001000101001100000000101001101111101110'
字符串中提取數字的函數。這里不需要填充;只要您的輸入序列為32個字母或更少,則結果整數將適合無符號8字節整數表示形式.在上面的輸出示例中,我使用format()字符串分別將該整數值格式化為十六進制和二進制字符串,然后將這些表示形式零填充到64位數字的正確位數.
為了衡量這是否更快,讓我們隨機抽取一百萬個測試字符串(每個字符串長28個字符):
>>> from random import choice
>>> testvalues = [''.join([choice('ATCG') for _ in range(28)]) for _ in range(10 ** 6)]
列表去除重復元素python,在使用2.9 GHz Intel Core i7的Macbook Pro和Python 3.6.5上,上述功能可以在3/4秒內產生100萬次轉換:
>>> from timeit import timeit
>>> timeit('seq_to_int(next(tviter))', 'from __main__ import testvalues, seq_to_int; tviter=iter(testvalues)')
0.7316284350017668
python菜鳥教程,因此,每個通話為0.73微秒.
(以前,我提倡使用預計算版本,但經過試驗,我采用了以4為底的想法).
要將其與到目前為止發布的其他方法進行比較,還需要調整一些方法以產生整數,并將其包裝到函數中:
def seq_to_int_alexhall_a(seq, mapping={'A': b'00', 'C': b'01', 'G': b'10', 'T': b'11'}):
python如何將數字轉化為字符串、return int(b''.join(map(mapping.__getitem__, seq)), 2)
def seq_to_int_alexhall_b(seq, mapping={'A': b'00', 'C': b'01', 'G': b'10', 'T': b'11'}):
return int(b''.join([mapping[c] for c in seq]), 2)
def seq_to_int_jonathan_may(seq, mapping={'A': 0b00, 'C': 0b01, 'G': 0b10, 'T': 0b11}):
python字符串轉換成整數。result = 0
for char in seq:
result = result << 2
result = result | mapping[char]
python將輸入的字符串轉換為數字。return result
然后我們可以比較這些:
>>> testfunctions = {
... 'Alex Hall (A)': seq_to_int_alexhall_a,
... 'Alex Hall (B)': seq_to_int_alexhall_b,
... 'Jonathan May': seq_to_int_jonathan_may,
... # base_decode as defined in https://stackoverflow.com/a/50239330
... 'martineau': base_decode,
... 'Martijn Pieters': seq_to_int,
... }
>>> setup = """\
... from __main__ import testvalues, {} as testfunction
... tviter = iter(testvalues)
... """
>>> for name, f in testfunctions.items():
... res = timeit('testfunction(next(tviter))', setup.format(f.__name__))
... print(f'{name:>15}: {res:8.5f}')
...
Alex Hall (A): 2.17879
Alex Hall (B): 2.40771
Jonathan May: 3.30303
martineau: 16.60615
Martijn Pieters: 0.73452
我提出的以4為基的方法很容易贏得這一比較.
版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。
工作时间:8:00-18:00
客服电话
电子邮件
admin@qq.com
扫码二维码
获取最新动态