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?

ThePyGuy
  • 17,779
  • 5
  • 18
  • 45
Ainulindalë
  • 171
  • 1
  • 5
  • 1
    what have you tried ? – Chiheb Nexus Apr 23 '21 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. – Samwise Apr 23 '21 at 18:05
  • 1
    This (at least the 1st part of it) can be achieved in one line using https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions. – CristiFati Apr 23 '21 at 18:06

3 Answers3

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']]
ThePyGuy
  • 17,779
  • 5
  • 18
  • 45
1

You could use splitlines.

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

output

[['Test1', 'Test2'], ['Grade A', 'Grade B']]
Buddy Bob
  • 5,829
  • 1
  • 13
  • 44
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))
Dugbug
  • 454
  • 2
  • 11