如何从Python字符串中一次提取三个字符?

2024-10-02 10:20:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我想写一个函数,它接受一长串字符(一个像‘ugguuauuaugguuaaugguuu’这样的蛋白质序列),并一次从中提取三个字符(即密码子)。它可以依次返回每组三个字符,也可以返回包含所有三个字符的列表。两种方法都可以。但我在弄清楚如何干净地完成这件事上遇到了一些困难

以下是我目前掌握的情况:

def get_codon_list(codon_string):
    codon_start = 0
    codon_length = 3
    codon_end = 3
    codon_list = []
    for x in range(len(codon_string) // codon_length):
        codon_list.append(codon_string[codon_start:codon_end])
        codon_start += codon_length
        codon_end += codon_length
    return codon_list

它可以返回密码子列表,但似乎效率很低。如果有更好的方法,我不喜欢使用硬编码的数字和递增的变量。我也不喜欢使用for循环,因为它实际上不使用循环中的变量。这似乎不是一个正确的使用它

有没有关于如何改进这一点的建议,或者是使用特定的函数/模块,或者只是使用更好的Pythonic技术

谢谢


Tags: 方法函数列表forstring蛋白质字符start
3条回答

您可以使用列表理解,每次从字符串中获取长度为3的片段

>>> s="UGGUGUUAUUAAUGGUUU"
>>> res = [s[i:i+3] for i in range(0,len(s),3)]
>>> res
['UGG', 'UGU', 'UAU', 'UAA', 'UGG', 'UUU']

{}石斑鱼配方非常适合({a1}):

In [1]: from itertools import zip_longest

In [2]: def grouper(iterable, n, fillvalue=None):
   ...:     "Collect data into fixed-length chunks or blocks"
   ...:     # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
   ...:     args = [iter(iterable)] * n
   ...:     return zip_longest(*args, fillvalue=fillvalue)
   ...:

In [3]: list(grouper('UGGUGUUAUUAAUGGUUU', 3))
Out[3]:
[('U', 'G', 'G'),
 ('U', 'G', 'U'),
 ('U', 'A', 'U'),
 ('U', 'A', 'A'),
 ('U', 'G', 'G'),
 ('U', 'U', 'U')]

只需使用^{}函数的step参数即可避免维护变量:

def get_codon_list(codon_string):
    codon_length = 3
    codon_list = []

    for codon_start in range(0, len(codon_string), codon_length):
        codon_end = codon_start + codon_length
        codon_list.append(codon_string[codon_start:codon_end])

    return codon_list

然后它可以变成一个列表:

def get_codon_list(codon_string):
    codon_length = 3

    codon_list = [codon_string[x:x+codon_length] for x in range(0, len(codon_string), codon_length)]

    return codon_list

相关问题 更多 >

    热门问题