Home > Net >  HOW TO SPLIT 1D STRING LIST INTO 2D LIST?
HOW TO SPLIT 1D STRING LIST INTO 2D LIST?

Time:10-30

I can slice lists like [a,b,c,d] into [[a,b],[c,d]], but I'm having trouble slicing more complex ones.

I want to slice the following list ['Jane B 82\n', 'Violet C 76\n', 'Max A 93\n']

into [[Jane, B, 82], [Violet, C, 76], [Max, A, 93]]. How do I slice a list of strings?...(if that's the correct way to put it...)

CodePudding user response:

You're not really slicing here. You are trying to transform each list element into something else. You could use map to do that. For instance:

arr = ['Jane B 82\n', 'Violet C 76\n', 'Max A 93\n']
new_list = list(map(lambda x: x.strip().split(' '), arr))
print(new_list)

output

[['Jane', 'B', '82'], ['Violet', 'C', '76'], ['Max', 'A', '93']]

CodePudding user response:

You really just need simple list concatenation

list =  ['Jane B 82\n', 'Violet C 76\n', 'Max A 93\n']

result = [[x.strip('\n')] for x in list]

print(result)
[['Jane B 82'], ['Violet C 76'], ['Max A 93']]

The x.strip('\n') portion is just removing the newline character. Then you here you are saying "for each item x in list remove the newline character and put it in its own list, then add that character the the list result

CodePudding user response:

Using list comprehension:

a = ['Jane B 82\n', 'Violet C 76\n', 'Max A 93\n']
b = [i.strip("\n").split(" ") for i in a]
print(b)

Output:

[['Jane', 'B', '82'], ['Violet', 'C', '76'], ['Max', 'A', '93']]
  • Related