将字符串转换为tup

2024-10-01 19:31:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要编写一个函数,它接受一个字符串'(1,2,3,4,5),(5,4,3,2,1)'并返回每个元组的第一个和最后一个元素的元组列表,[(1,5),(5,1)]。 我在想:

def f(givenstring):
    a=givenstring.split(',')
    for i in a[0:-1]:
        tuple(int(i[0,-1]))

但在这里我被困住了。。


Tags: 函数字符串in元素列表fordefint
3条回答

在这种情况下,ast模块可能很有用:

>>> from ast import literal_eval
>>> s = '(1,2,3,4,5),(5,4,3,2,1)'
>>> my_tuples = literal_eval(s)
>>> my_tuples
((1, 2, 3, 4, 5), (5, 4, 3, 2, 1))

因此,my_tuples有一个元组与字符串的元组。现在,我们可以使用列表理解获得所有元组的第一个和最后一个元素:

>> new_tuples = [(t[0], t[-1]) for t in my_tuples]
>>> new_tuples
[(1, 5), (5, 1)]

您可以使用^{}

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.

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)]

您可以使用eval。我想这是最短的。

>>> s = '(1,2,3,4,5),(5,4,3,2,1)'
>>> ts = eval(s)
>>> ts
((1, 2, 3, 4, 5), (5, 4, 3, 2, 1))
>>> tsp = [(el[0],el[-1]) for el in ts]
>>> tsp
[(1, 5), (5, 1)]

不过,使用eval并不是一个好的做法。

另一个选项是使用re模块解析字符串。

>>> a = re.findall('\([^)]*\)',s)
>>> a
['(1,2,3,4,5)', '(5,4,3,2,1)']

Regexp模式意味着:

\( #opening parenthesis
[^)]* #from 0 to infinite symbols different from )
\) #closing parenthesis

是的。

>>> b = [el.strip('()') for el in a]
>>> b
['1,2,3,4,5', '5,4,3,2,1']
>>> c = [el.split(',') for el in b]
>>> c
[['1', '2', '3', '4', '5'], ['5', '4', '3', '2', '1']]
>>> d = [tuple(int(el2) for el2 in el) for el in c]
>>> d
[(1, 2, 3, 4, 5), (5, 4, 3, 2, 1)]

此外,您还可以执行以下操作:

>>> [tuple(int(i) for i in el.strip('()').split(',')) for el in s.split('),(')]
[(1, 2, 3, 4, 5), (5, 4, 3, 2, 1)]

这种方法根本不需要模块。但是它不是很健壮(如果输入字符串有一些不一致,例如括号和逗号之间的空格...), (...,那么noting就可以工作)。

相关问题 更多 >

    热门问题