我有这样一个字符串:
'(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']
我有一种感觉,我走了比必要的更长的路,所以非常欢迎提供更简单的方法。请耐心等待,我是 Python 的新手。谢谢。
最佳答案
def parseAnnotation(annotation):
return [tuple(pair[1:-1].split('..')) for pair in annotation.split(',')]
编辑:literal_eval
较慢(而且 Pythonic 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
另一个编辑:忘记了您需要 int
。
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/