2014-01-30 49 views
0

如何删除 “(” “)” 的形式如何从列表中的元组中删除字符?

[('(10', '40)'), ('(40', '30)'), ('(20', '20)')] 

由蟒蛇?

+5

你能否提供更多代码来证明你是如何达到这一点的?这个问题可能与您的数据生成方式有关,并且可能会以不同的方式处理,以避免必须解决此“问题”。 –

+1

我尝试格式化字符串:((10 40),(40 30),(20 20),(30 10))到元组列表。 – user7172

+0

@flup你是对的,我删除我的评论。 –

回答

1

根据你目前如何储存该列表:

def to_int(s): 
    s = ''.join(ch for ch in s if ch.isdigit()) 
    return int(s) 

lst = [('(10', '40)'), ('(40', '30)'), ('(20', '20)')] 

lst = [(to_int(a), to_int(b)) for a,b in lst] # => [(10, 40), (40, 30), (20, 20)] 

import ast 

s = "[('(10', '40)'), ('(40', '30)'), ('(20', '20)')]" 
s = s.replace("'(", "'").replace(")'", "'") 
lst = ast.literal_eval(s)    # => [('10', '40'), ('40', '30'), ('20', '20')] 
lst = [(int(a), int(b)) for a,b in lst] # => [(10, 40), (40, 30), (20, 20)] 
0
>>> L = [('(10', '40)'), ('(40', '30)'), ('(20', '20)')] 
>>> [tuple((subl[0].lstrip("("), subl[1].rstrip(")"))) for subl in L] 
[('10', '40'), ('40', '30'), ('20', '20')] 

或者,如果你婉的数字在你的元组最终是int S:

>>> [tuple((int(subl[0].lstrip("(")), int(subl[1].rstrip(")")))) for subl in L] 
[(10, 40), (40, 30), (20, 20)] 
0

您可以致电.strip('()')个别项目(如果他们是字符串,如在您的示例中)去除尾随()

有以应用在单要素多种方式:

列表理解(最Python的)

a = [tuple(x.strip('()') for x in y) for y in a] 

maplambda(有趣的)

的Python 3 :

def cleanup(a: "list<tuple<str>>") -> "list<tuple<int>>": 
    return list(map(lambda y: tuple(map(lambda x: x.strip('()'), y)), a)) 

a = cleanup(a) 

的Python 2:

def cleanup(a): 
    return map(lambda y: tuple(map(lambda x: x.strip('()'), y)), a) 

a = cleanup(a) 
0

过程中的原始字符串来代替。我们称之为a

a='((10 40), (40 30), (20 20), (30 10))',您可以拨打

[tuple(x[1:-1].split(' ')) for x in a[1:-1].split(', ')] 

从字符串的[1:-1]装饰斗拱,split而分裂成字符串字符串列表。 for是一种理解。

0
s = "((10 40), (40 30), (20 20), (30 10))" 
print [[int(x) for x in inner.strip('()').split()] for inner in s.split(',')] 

# or if you actually need tuples: 
tuple([tuple([int(x) for x in inner.strip('()').split()]) for inner in s.split(',')]) 
2

直截了当,使用列表理解和literal_eval。

>>> from ast import literal_eval 
>>> tuple_list = [('(10', '40)'), ('(40', '30)'), ('(20', '20)')] 
>>> [literal_eval(','.join(i)) for i in tuple_list] 
[(10, 40), (40, 30), (20, 20)]