繁体   English   中英

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

[英]How to remove character from tuples in list?

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

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

通过python?

直接使用列表理解和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)]

根据您当前存储列表的方式:

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)]
>>> 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 ,则可以:

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

您可以在单个项目(如示例中为字符串.strip('()')上调用.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)

而是处理原始字符串。 让我们把它叫做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是一个理解。

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(',')])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM