Jain
Jain

Reputation: 85

How to convert a list with strings into a 2D list

I have a list like this:

list = ['aa#1#ll', 'bb#2#ff', 'cc#3#ff']

I want to convert it to a 2D list in this format

list2 = [['aa', '1', 'll'], ['bb', '2', 'ff'], ['cc', '3', 'ff']]

How can I do this in Python 3?

Upvotes: 1

Views: 280

Answers (1)

Anis R.
Anis R.

Reputation: 6902

You can use Python's split(delimiter) method inside a generator:

list2 = [x.split("#") for x in list]

Explanation: Here, for each string x in the original list, we are calling x.split("#") on it, which will give a list of substrings that are separated by hashes in x, and we are adding the result to the list list2.

Upvotes: 5

Related Questions