我有一根这样的绳子:

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

我想让它看起来像这样:
[(459, 521), (1834, 2736)]

也就是说,有值的元组列表,而不是字符串。
这就是我到目前为止想到的:
def parseAnnotation(annotation):
thing=[]
number=""
for c in annotation:
    if c.isdigit()==True:
        number=number+c
    else:
        thing.append(number)
        number=""
thing.append(number)
thing = filter(None, thing)
return thing

输出:
['459', '521', '1834', '2736']

我有一种感觉,我走了一条比必要的更长的路,所以对更简单的方法的投入是非常受欢迎的。请容忍我,我对蟒蛇很陌生。谢谢。

最佳答案

def parseAnnotation(annotation):
    return [tuple(pair[1:-1].split('..')) for pair in annotation.split(',')]

 
编辑:literal_eval速度较慢(而且在IMO中没有蟒蛇般的速度):
In [4]: %timeit list(ast.literal_eval(strs.replace('..',',')))
100000 loops, best of 3: 17.8 us per loop

In [5]: %timeit [tuple(pair[1:-1].split('..')) for pair in strs.split(',')]
1000000 loops, best of 3: 1.22 us per loop

 
另一个编辑:忘记了你需要ints
def parseAnnotation(annotation):
    return [tuple(map(int, pair[1:-1].split('..'))) for pair in annotation.split(',')]

这有点不可读,我们把它写成一个循环:
def parseAnnotation(annotation):
    result = []
    for pair in annotation.split(','):
        a, b = pair[1:-1].split('..')
        result.append( (int(a), int(b)) )
    return result

您决定它是否需要处理无效的输入。

关于python - 将AF字符串更改为具有值的元组列表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14069890/

10-09 17:11