-4

Original list:

lines = [['Name0, Location0', 'Phone number0'], ['Name1, Location1', 'Phone number1']]

I want to get new list as below:

newLines = [['Name0', 'Location0', 'Phone number0'], ['Name1', 'Location1', 'Phone number1']]  

I tried code below but it is not work (How to split elements in list?):

for line in lines:
    for token in line.split(', '):
        result.append(token)
print(result)

How to make it work?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Thet Cartter
  • 80
  • 1
  • 7

4 Answers4

0

You should know there are two nested list, so there should be two nested for loop to iterate the list. And you should use another for loop to iterate the split() result. The code may be like this:

lines = [['Name0, Location0', 'Phone number0'],
         ['Name1, Location1', 'Phone number1']]
result = []
for line in lines:
    result.append([])
    for fields in line:
        for token in fields.split(', '):
            result[-1].append(token)
print(result)

The output:

[['Name0', 'Location0', 'Phone number0'], ['Name1', 'Location1', 'Phone number1']]
Jason Pan
  • 702
  • 7
  • 21
0

You would have to iterate the strings in the sub-lists first before you can split each of the strings into tokens:

[[token for tokens in line for token in tokens.split(', ')] for line in lines]

This returns:

[['Name0', 'Location0', 'Phone number0'], ['Name1', 'Location1', 'Phone number1']]
blhsing
  • 91,368
  • 6
  • 71
  • 106
0

First you need to loop through the inner array as well, as it looks like you'll be getting an error for trying to split a list. As the split will be actioning on this line:

['Name0, Location0', 'Phone number0']

So you need another loop to action on the strings like:

result = []
# loop the array 
for line in lines:
    # If you want to keep the inner arrays, reset each loop 
    current = []
    # Now loop the inner array
    for item in line:
        for token in item.split(', '):
            # Add the items to an array
            current.append(token)
    # Add these inner arrays to the larger array
    result.append(current)
difurious
  • 1,523
  • 3
  • 19
  • 32
0

Try This

lines = [['Name0, Location0', 'Phone number0'], ['Name1, Location1', 'Phone number1']]


newLine = []


for line in lines:
    temp = []
    for element in line:
        temp.extend(element.split(', '))
    newLine.append(temp)
Gokul
  • 39
  • 3