When it is required to convert a list of strings with a delimiter to a list of tuple, a list comprehension, the ‘tuple’ method, and the ‘split’ method are used.
Example
Below is a demonstration of the same −
my_list = ["21$12", "33$24$48$69", "14$10$44"] print("The list is :") print(my_list) key = "$" print("The key is :") print(key) my_result = [tuple(int(element) for element in sub.split(key)) for sub in my_list] print("The result is :") print(my_result)
Output
The list is : ['21$12', '33$24$48$69', '14$10$44'] The key is : $ The result is : [(21, 12), (33, 24, 48, 69), (14, 10, 44)]
Explanation
A list of string values is defined and is displayed on the console.
A key value is defined and displayed on the console.
A list comprehension is used to iterate over the list.
It is split based on the ‘key’ that was previously defined.
It is then converted into an integer and then to a list of tuple.
This is assigned to a variable.
This is displayed as output on the console.