Convert a list of strings to a list of tuples in python

后端 未结 3 477
囚心锁ツ
囚心锁ツ 2021-01-19 19:17

I have a list of strings in this format:

[\'5,6,7\', \'8,9,10\']

I would like to convert this into the format:

[(5,6,7), (8         


        
3条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-19 20:03

    The following solution is for me the most readable, perhaps it is for others too:

    a = ['5,6,7', '8,9,10']          # Original list
    b = [eval(elem) for elem in a]   # Desired list
    
    print(b)
    

    Returns:

    [(5, 6, 7), (8, 9, 10)]

    The key point here being the builtin eval() function, which turns each string into a tuple. Note though, that this only works if the strings contain numbers, but will fail if given letters as input:

    eval('dog')
    
    NameError: name 'dog' is not defined
    

提交回复
热议问题