converting string to tuple

前端 未结 3 2119
栀梦
栀梦 2020-11-29 09:09

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 think

3条回答
  •  臣服心动
    2020-11-29 09:34

    In this case, the ast module could be useful:

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

    So, my_tuples has a tuple with the tuples of your string. Now, we can get the first and last element of all your tuples using a list comprehension:

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

提交回复
热议问题