如何删除“(”,“)”表格
[('(10', '40)'), ('(40', '30)'), ('(20', '20)')]
by python?
答案 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]
map
和lambda
(有趣的是看到)
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(',')])