1

I've got a text file like this:

1;2;3;4
5;6;7;8

And I'd like to transform it to:

[[1,2,3,4],[5,6,7,8]]

Using Python, how can i achieve this?*

Andrew Walker
  • 40,984
  • 8
  • 62
  • 84

5 Answers5

7

You can use the following:

data = [[int(i) for i in line.split(';')] for line in open(filename)]

Alternative using the csv module:

import csv
data = [[int(i) for i in ln] for ln in csv.reader(open(filename), delimiter=';')]

If lists of strings are acceptable:

data = [line.split(';') for line in open(filename)]

Or the csv equivalent:

data = list(csv.reader(open(filename), delimiter=';'))
Andrew Clark
  • 202,379
  • 35
  • 273
  • 306
  • by the way , i ve got a huge data and i tried to apply csv module to it and i got "MemoryError" , how can i handle it? –  Dec 21 '12 at 01:14
3

As a multi-line string:

>>> s = """1;2;3;4
5;6;7;8"""

>>> [[int(x) for x in a.split(';')] for a in s.splitlines()]
[[1, 2, 3, 4], [5, 6, 7, 8]]
Alex L
  • 8,748
  • 5
  • 49
  • 75
2

As your data seems to be some sort of CSV like data, why not use python's csv parsing module? This handles encoding and supports delimiters all for free.

If you just want some code, use a list comprehension and split using the split method of str:

result = [line.split(';') for line in text.split("\n")]
nemo
  • 55,207
  • 13
  • 135
  • 135
2

'1;2;3;4'.split(';') will produce the list [1, 2, 3, 4] from the string '1;2;3;4', so you just need to do that for each line in your file:

def split_lists(filepath, sep=';'):
    with open(filepath) as f:
        line_lists = []
        for line in f:
            line_lists.append(line.split(sep))
        return line_lists

Or more compactly with a comprehension

def split_lists(filepath, sep=';'):
    with open(filepath) as f:
        return [line.split(sep) for line in f]
Matt Tenenbaum
  • 1,321
  • 10
  • 11
0

thanks for the interesting question, can be resolved by 2 map and one for loop

s='1;2;3;4\n5;6;7;8'
map(lambda seq: [int(i) for i in seq], map(lambda x:x.split(';'), s.split('\n')))
Houcheng
  • 2,674
  • 25
  • 32