Home > Back-end >  python, 2 line string to 2 dimension array conversion
python, 2 line string to 2 dimension array conversion

Time:11-18

import numpy as np

text = '''1, 3, 5, 7, 9
          8, 6, 4, 2, 0'''

data = []

\n exists in after 9

I want an output like this

data = [[1,3,5,7,9],[8,6,4,2,0]]

numbers in data is int, that converted into int from string

CodePudding user response:

You can use list comprehension with splitlines and split:

text = '''1, 3, 5, 7, 9
          8, 6, 4, 2, 0'''

data = [[int(x) for x in line.split(', ')] for line in text.splitlines()]
print(data) # [[1, 3, 5, 7, 9], [8, 6, 4, 2, 0]]

CodePudding user response:

For easy input into numpy use io.StringIO

>>> from io import StringIO
>>> np.array(StringIO(text).read())
[[1, 3, 5, 7, 9]
 [8, 6, 4, 2, 0]]

You can use ast.literal_eval

>>> from ast import literal_eval
>>> [list(literal_eval(s)) for s in text.split('\n')]
[[1, 3, 5, 7, 9], [8, 6, 4, 2, 0]]

CodePudding user response:

You can also use map() to do this

text = '''1, 3, 5, 7, 9
          8, 6, 4, 2, 0'''
lst = list(map(int, text.replace(",","").split()))
print([lst[:5],lst[5:]])
  • Related