How to split a nested list into separate lists?

Question:

I have a list as follows

[['Norm,Macdonald', '61', '459000'], ['Paul,McCartney', '79', '2789000'], ['Samuel,Hui', '73', '538000']]

For the desired output it would be something like

[['Norm', 'Macdonald', '61', '459000'], ['Paul', 'McCartney', '79', '2789000'], ['Samuel', 'Hui', '73', '538000']]

How should I split it to make it look like this?

I have tried using .split(‘,’) but it will return a nested list within the original list position i.e.

[[['Norm', 'Macdonald'], '61', '459000'], [['Paul', 'McCartney'], '79', '2789000'], [['Samuel', 'Hui'], '73', '538000']]
Asked By: codingnewbie

||

Answers:

You can do this:

my_list = [['Norm,Macdonald', '61', '459000'], ['Paul,McCartney', '79', '2789000'], ['Samuel,Hui', '73', '538000']]

new_list = []
for l in my_list:
    temp = []
    for e in l:
        temp.extend(e.split(","))
    new_list.append(temp)
new_list

Another way:

new_list = [[s for s in item[0].split(',')] + item[1:] for item in my_list]

Result:

[['Norm', 'Macdonald', '61', '459000'],
 ['Paul', 'McCartney', '79', '2789000'],
 ['Samuel', 'Hui', '73', '538000']]

One way to do this is:

l = [['Norm,Macdonald', '61', '459000'], ['Paul,McCartney', '79', '2789000'], ['Samuel,Hui', '73', '538000']]
new_l = [[*x[0].split(","), *x[1:]] for x in l]
print(new_l)

This will print

[['Norm', 'Macdonald', '61', '459000'], ['Paul', 'McCartney', '79', '2789000'], ['Samuel', 'Hui', '73', '538000']]
Answered By: Tom McLean

using join and split

my_list = [['Norm,Macdonald', '61', '459000'], ['Paul,McCartney', '79', '2789000'], ['Samuel,Hui', '73', '538000']]
solution = [','.join(i).split(',') for i in my_list]
print(solution)
# output -> [['Norm', 'Macdonald', '61', '459000'], ['Paul', 'McCartney', '79', '2789000'], ['Samuel', 'Hui', '73', '538000']]
Answered By: sahasrara62

You can try list-comprehensions with split

new_list = [[item for el in sub for item in el.split(',')] for sub in your_list]
print(new_list )
Answered By: Bhargav

You can use ','.join(the_list) and split(',') together as in the first function.

the second function runs the first function for each list in your nested list and substitutes the internal lists with their unpacked versions.

def split_all_by(the_list, char):
    joined = char.join(the_list)
    splitted = joined.split(char)
    return splitted


def split_internal_lists_by(the_nested_list, char):
    for index in range(len(the_nested_list)):
        internal_list = the_nested_list[index]
        the_nested_list[index] = split_all_by(internal_list, ',')
    
    return the_nested_list


nested_list = [['Norm,Macdonald', '61', '459000'], ['Paul,McCartney', '79', '2789000'], ['Samuel,Hui', '73', '538000']]
result = split_internal_lists_by(nested_list, ',')
print(result)
Answered By: The ESY
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.