Skip to main content
 首页 » 编程设计

python之如何从字符串中创建元组列表

2025年05月04日17mengfanrong

Write a function

def parseAnnotation(annotation):

that takes a string annotation as argument. This string describes the location of the CDS in the sequence in the following manner (start..end),(start..end) etc. E.g. the string '(459..521),(1834..2736)' specifies that the CDS is distributed in two exons with one part from base number 459 to base number 521 (both inclusive) and the remaining part from base number 1834 to base number 2736 (both inclusive). The function must return a list with a tuple for each CDS part, each with a start and end value.

Example usage: parseAnnotation('(459..521),(1834..2736)') should return [(459, 521), (1834, 2736)]

我的尝试:

def parseAnnotation(annotation): 
lst = [] 
for seq in annotation: 
    seq.replace("..", ",") 
    lst = seq 
    return annotation 
     
print parseAnnotation('(459..521), (1834..2736)') 

输出:

(459..521), (1834..2736) 

我能做什么?

请您参考如下方法:

字符串是不可变的,你应该将str.replace返回的字符串赋给一个变量。

>>> s = '(459..521), (1834..2736)' 
>>> new_s = s.replace('..', ',') 
>>> new_s 
'(459,521), (1834,2736)' 
>>> s                          #Still unchanged 
'(459..521), (1834..2736)' 

要获取元组列表,请使用 ast.literal_eval 和 list():

>>> from ast import literal_eval 
>>> list(literal_eval(new_s)) 
[(459, 521), (1834, 2736)]