Sometimes, while working with data, we can have problem in which we need to convert the data list which in string format to list of tuples. This can occur in domains in which we have cross type inputs. Lets discuss certain ways in which this task can be performed.
Method #1 : Using loop + eval() The combination of above methods can be used to solve this task. In this we remake the string after processing for input to eval function to convert to Tuple lists.
Python3
# Python3 code to demonstrate working of # Convert String Records to Tuples Lists # Using loop + eval() # initializing string test_str = '[(gfg, ), (is, ), (best, )]' # printing original string print ( "The original string is : " + test_str) # Convert String Records to Tuples Lists # Using loop + eval() res = '' temp = True for chr in test_str: if chr = = '(' and temp: res + = '("' temp = False continue if chr = = ', ' and not temp: res + = '"' temp = True res + = chr res = eval (res) # printing result print ( "The list of Tuples is : " + str (res)) |
The original string is : [(gfg, ), (is, ), (best, )] The list of Tuples is : [('gfg', ), ('is', ), ('best', )]
Time complexity: O(n), where n is the length of the input string.
Auxiliary space: O(n), as we are creating a new string ‘res’ which can be of length n, and then converting it to a list of tuples.
Method #2 : Using regex + list comprehension The combination of above functionalities is used to perform this task. In this, we employ regex function to perform the task of resolving the String and list comprehension helps in reconstruction of record list.
Python3
# Python3 code to demonstrate working of # Convert String Records to Tuples Lists # Using regex + list comprehension import re # initializing string test_str = '[(gfg, ), (is, ), (best, )]' # printing original string print ( "The original string is : " + test_str) # Convert String Records to Tuples Lists # Using regex + list comprehension regex = re. compile (r '\((.*?)\)' ) temp = regex.findall(test_str) res = [ tuple (sub.split( ', ' )) for sub in temp] # printing result print ( "The list of Tuples is : " + str (res)) |
The original string is : [(gfg, ), (is, ), (best, )] The list of Tuples is : [('gfg', ''), ('is', ''), ('best', '')]
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #3: Using Recursive method.
Algorithm:
- Define the convert_to_tuple function that takes four arguments – string, i, length, and tuples.
- Define the start variable to be the current index i.
- While the current index i is less than the length of the string length, do the following:
a. If the current character is an opening bracket ‘(‘, call the convert_to_tuple function recursively with the new index value i+1.
b. If the current character is a closing bracket ‘)’, append the substring from the starting index start to the current index i as a tuple in the tuples list, and return the current index i.
c. Increment the current index i by 1. - Return the current index i.
Python3
# Python3 code to demonstrate working of # Convert String Records to Tuples Lists # Using recursion # Function to find matching closing bracket and # convert it to a tuple def convert_to_tuple(string, i, length, tuples): start = i while i < length: if string[i] = = '(' : i = convert_to_tuple(string, i + 1 , length, tuples) elif string[i] = = ')' : tuples.append( tuple (string[start :i].split( ', ' ))) return i i + = 1 return i # initializing string test_str = '[(gfg, ), (is, ), (best, )]' # printing original string print ( "The original string is : " + test_str) # Convert String Records to Tuples Lists # Using recursion tuples = [] convert_to_tuple(test_str, 0 , len (test_str), tuples) # printing result print ( "The list of Tuples is : " + str (tuples)) #this code contributed by tvsk |
The original string is : [(gfg, ), (is, ), (best, )] The list of Tuples is : [('gfg', ''), ('is', ''), ('best', '')]
Time Complexity: O(n), where n is the length of the input string. This is because the function iterates over each character in the input string exactly once and performs constant time operations at each iteration. The recursive calls also add constant time to the overall time complexity.
Auxiliary Space: O(m), where m is the number of tuples in the input string. This is because the function creates a new tuple for each pair of opening and closing brackets encountered, and stores them in the tuples list. The maximum size of the tuples list is equal to the number of tuples in the input string, which is proportional to the size of the input.
Method #4: Using json.loads()
- Import the json module.
- Initialize the test_str variable to a string containing JSON-formatted data.
- Use json.loads() to parse the JSON-formatted data into a Python list of lists.
- Use a list comprehension to create a new list of tuples where each tuple contains the first element of the corresponding sublist from step 3.
- Filter the resulting list to remove any tuples that have an empty string as the first element.
- Print the resulting list of tuples.
Python3
import json test_str = '[["gfg", ""], ["is", ""], ["best", ""]]' tuple_list = [(x[ 0 ],) for x in json.loads(test_str)] print (tuple_list) #This code is contributed by Vinay Pinjala. |
[('gfg',), ('is',), ('best',)]
Time complexity:
json.loads() has a time complexity of O(n) where n is the length of the input string.
The list comprehension has a time complexity of O(n), where n is the length of the input list.
The filter has a time complexity of O(m), where m is the number of elements in the resulting list (which could be less than n if some elements are filtered out).
Therefore, the overall time complexity of the code is O(n+m).
Space complexity:
The test_str variable takes up O(n) space, where n is the length of the input string.
The resulting list of tuples takes up O(m) space, where m is the number of elements in the resulting list (which could be less than n if some elements are filtered out).
The json_list variable takes up O(n) space, where n is the length of the input string.
Therefore, the overall space complexity of the code is O(n+m).
Method #5: Using ast.literal_eval()
Step-by-step approach:
- Import the ast module.
- Define the string that needs to be converted into a list of tuples.
- Call the ast.literal_eval() function with the string as the argument.
- The ast.literal_eval() function evaluates the string as a Python expression and returns the resulting object.
- Assign the result to a variable.
- Print the result.
Below is the implementation of the above approach:
Python3
import ast # initializing string test_str = '[("gfg", ), ("is", ), ("best", )]' # printing original string print ( "The original string is : " + test_str) # Convert String Records to Tuples Lists # Using ast.literal_eval() res = ast.literal_eval(test_str) # printing result print ( "The list of Tuples is : " + str (res)) |
The original string is : [("gfg", ), ("is", ), ("best", )] The list of Tuples is : [('gfg',), ('is',), ('best',)]
Time complexity: The time complexity of ast.literal_eval() is O(n), where n is the length of the string to be evaluated. Therefore, the time complexity of this method is O(n).
Auxiliary Space: O(n), where n is the length of the string to be evaluated. This is because the ast.literal_eval() method creates a parse tree to evaluate the string, and the size of the parse tree is proportional to the size of the input string.