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

标签 python string list tuples

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_evallist():

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

关于python - 如何从字符串中创建元组列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20932298/

相关文章:

c++ - 初始化字符串 vector 数组时出错

c++ - 如何确定中间包含 "\0"的 std::string 的长度?

c - 字符串的第一个字符在哪里?

python - 我有 2 个列表,我想合并它们,答案应该如下所示

python - 如何在 Google Colab 上创建和使用自定义 OpenAI Gym 环境?

python - 在 Visual Studio 下运行 Python 的单元测试总是这么慢吗?

python - 使用子图而不是 matplotlib 中的图形来控制鼠标单击事件

python - 排序 Swagger 标签

python - 嵌套列表到嵌套字典

python - 列表列表 : why does changing value at a[1][0] also change a[0][0]?