如何从列表中的元组中删除字符?

时间:2014-01-30 22:33:12

标签: python list tuples

如何删除“(”,“)”表格

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

by python?

6 个答案:

答案 0 :(得分:2)

直截了当,使用list comprehension和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)]

答案 1 :(得分: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)]

答案 2 :(得分: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)]

答案 3 :(得分:0)

您可以针对单个项目(如果它们是字符串,如您的示例中)调用.strip('()')来删除尾随()

有多种方法可以在单个元素上应用它:

列表理解(大多数pythonic)

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)

答案 4 :(得分: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是一种理解。

答案 5 :(得分: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(',')])