Rom Rom Rom Rom - 4 months ago 6
Python Question

Save in a array the datas of a text file

i want to do this in Python : i have this file like this :

1 10
2 50
3 8
4 9
5 16
6 18


And i would like to save this datas like that in two arrays :

A = [1 2 3 4 5 6]
B = [10 50 8 9 16 18]


I don't know how to do this :/

Thank you

Answer

We can do this with zip().

This function returns a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. The returned list is truncated in length to the length of the shortest argument sequence. When there are multiple arguments which are all of the same length, zip() is similar to map() with an initial argument of None. With a single sequence argument, it returns a list of 1-tuples. With no arguments, it returns an empty list.

Let me show you by example:

In [1]: filedata = """1  10
   ...: 2  50
   ...: 3   8
   ...: 4   9
   ...: 5  16
   ...: 6  18
   ...: """

In [2]: filedata
Out[2]: '1  10 \n2  50 \n3   8\n4   9\n5  16\n6  18\n'

In [3]: data = []
   ...: for line in fdata.splitlines():
   ...:     lineParts  = line.strip().split()
   ...:     data.append(lineParts)
   ...:

In [4]: data
Out[4]: [['1', '10'], ['2', '50'], ['3', '8'], ['4', '9'], ['5', '16'], ['6', '18']]

In [5]: zip(*data)
Out[5]: [('1', '2', '3', '4', '5', '6'), ('10', '50', '8', '9', '16', '18')]

Note that we use *data instead of data, to unpack each element in the list into a separate argument to zip().

Note that now we have a list of two tuple()s, and you wanted A and B to be lists, so here's how we do that, using map(), to change both tuple()s to list()s:

In [15]: (A, B) = map(list, zip(*data))

In [16]: A
Out[16]: ['1', '2', '3', '4', '5', '6']

In [17]: B
Out[17]: ['10', '50', '8', '9', '16', '18']

Edit: For clarity, the complete code is here:

filename = 'input.txt'

data = []
with open(filename, 'r') as fd:
    for line in fd:
        lineParts  = line.strip().split()
        data.append(lineParts)

(A, B) = map(list, zip(*data))