Python – To convert a list of strings with a delimiter to a list of tuple

PythonServer Side ProgrammingProgramming

When it is required to convert a list of strings with a delimiter to a list of tuples, a K value is set, and list comprehension along with the ‘split’ method is used.

Example

Below is a demonstration of the same −

my_list = ["33-22", "13-44-81-39", "42-10-42", "36-56-90", "34-77-91"]

print("The list is : " )
print(my_list)

print("The sorted list is ")
my_list.sort()
print(my_list)

K = "-"
print("The value of K is ")
print(K)

my_result = [tuple(int(element) for element in sub.split(K)) for sub in my_list]
print("The resultant list is : ")
print(my_result)

Output

The list is :
['33-22', '13-44-81-39', '42-10-42', '36-56-90', '34-77-91']
The sorted list is
['13-44-81-39', '33-22', '34-77-91', '36-56-90', '42-10-42']
The value of K is
-
The resultant list is :
[(13, 44, 81, 39), (33, 22), (34, 77, 91), (36, 56, 90), (42, 10, 42)]

Explanation

  • A list of strings is defined and is displayed on the console.

  • The list is sorted using a sort method and is displayed on the console.

  • The value for K is defined and displayed in the console.

  • A list comprehension is used to iterate over the list, and the value is split and converted to an integer and then to a tuple.

  • This is assigned to a result.

  • This is displayed as output on the console.

raja
Published on 13-Sep-2021 08:14:05
Advertisements