Raj
Raj

Reputation: 25

Elements within a list of lists

I have a below mentioned list:

a= ['1234,5678\n','90123,45678\n']

The expected output I'm working towards is this:

op = [['1234','5678'],['90123','45678']]

Basically a list of lists with individual elements referring to a particular column.

Using the below mentioned code i get the following output:

a = ['1234,5678\n','90123,45678\n']

new_list = []

for element in a:
    #remove new lines
    new_list.append(element.splitlines())
    
print(new_list)

output:[['1234,5678'], ['90123,45678']]

Any direction regarding this would be much appreciated.

Upvotes: 1

Views: 44

Answers (3)

blhsing
blhsing

Reputation: 106553

Since the strings in your input list appears to follow the CSV format, you can use csv.reader to parse them:

import csv
list(csv.reader(a))

This returns:

[['1234', '5678'], ['90123', '45678']]

Upvotes: 0

Pawan Jain
Pawan Jain

Reputation: 825

Try this:

a = [i.strip("\n").split(",") for i in a]

Upvotes: 0

user15801675
user15801675

Reputation:

Check this:

a= ['1234,5678\n','90123,45678\n']
a = ['1234,5678\n','90123,45678\n']

new_list = []

for element in a:
    #remove new lines
    new_list.append(element.strip("\n").split(","))
    
print(new_list)

Upvotes: 1

Related Questions