0

I have this list:

test_results = ['Test1\nTest2', 'Grade A\nGrade B'] 

I want to split the elements by the '\n' and save them in another list, like this:

test_results = [['Test 1, Grade A'], ['Test B', 'Grade B']] 

I am struggling to find a way to do it... can you help me?

3
  • 1
    what have you tried ? Commented Apr 23, 2021 at 18:05
  • 1
    test_results = [i.split('\n') for i in test_results] would be a starting point. You also probably want to look at zip for rotating the resulting list of lists. Commented Apr 23, 2021 at 18:05
  • 1
    This (at least the 1st part of it) can be achieved in one line using docs.python.org/3/tutorial/…. Commented Apr 23, 2021 at 18:06

3 Answers 3

2

You can use map with str.splitlines

>>> x = list(map(str.splitlines, test_results)) >>> x [['Test1', 'Test2'], ['Grade A', 'Grade B']] 

Now you can use zip to get what you exactly want:

>>> [[a,b] for a,b in zip(x[0], x[1])] [['Test1', 'Grade A'], ['Test2', 'Grade B']] 
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for letting me know, I did not take close look to that, I'll update the answer
@ChihebNexus, I think it matches the expected output now
1

You could use splitlines.

y = [x.splitlines() for x in test_results] 

output

[['Test1', 'Test2'], ['Grade A', 'Grade B']] 

2 Comments

PO is searching for this output: [['Test 1, Grade A'], ['Test B', 'Grade B']]
That's for sure a typo. Why would user want that?
0

There are many 1-liners, but this might be the easiest to understand

def split_list(list): for string in list: # For each string in my list list[list.index(string)] = string.split( "\n") # Splitting the string a "\n" return test_results test_results = ['Test1\nTest2', 'Grade A\nGrade B'] print(split_list(test_results)) 

1 Comment

Your output is wrong. PO is searching for this output: [['Test 1, Grade A'], ['Test B', 'Grade B']]

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.