将字符串转换为元组 [英] converting string to tuple
问题描述
我需要编写一个函数,它接受一个字符串 '(1,2,3,4,5),(5,4,3,2,1)' 并返回第一个和最后一个元素的元组列表每个元组,[(1,5),(5,1)].我在想:
I need to write a function that takes a string '(1,2,3,4,5),(5,4,3,2,1)' and returns a list of tuples of the 1st and last element of each tuple, [(1,5),(5,1)]. I was thinking:
def f(givenstring):
a=givenstring.split(',')
for i in a[0:-1]:
tuple(int(i[0,-1]))
但在这里我被卡住了..
but here I'm stucked..
推荐答案
您可以使用 ast.literal_eval()
:
You can use ast.literal_eval()
:
安全地计算表达式节点或包含 Python 表达式的字符串.提供的字符串或节点只能由以下 Python 文字结构组成:字符串、数字、元组、列表、字典、布尔值和无.
Safely evaluate an expression node or a string containing a Python expression. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.
这可用于安全地评估包含来自不受信任来源的 Python 表达式的字符串,而无需自己解析值.
This can be used for safely evaluating strings containing Python expressions from untrusted sources without the need to parse the values oneself.
在您的示例中:
from ast import literal_eval
s = '(1,2,3,4,5),(5,4,3,2,1)'
l = literal_eval(s)
print l
# ((1, 2, 3, 4, 5), (5, 4, 3, 2, 1))
print [(x[0], x[-1]) for x in l]
# [(1, 5), (5, 1)]
这篇关于将字符串转换为元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!