Rom Rom
Rom Rom

Reputation: 37

Save in an array the data from a text file

In Python, if I have the following file:

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

How would I save these data - in two arrays - like so?

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

Thank you

Upvotes: 0

Views: 98

Answers (2)

boardrider
boardrider

Reputation: 6185

This pure Python3 code is understandable to a beginner:

#!/usr/bin/env python3

first = list()
second = list()

with open("/tmp/tmp.txt", "r") as data:
    for a in data.readlines():
        _1, _2 = a.split()
        first.append(int(_1))
        second.append(int(_2))

print("A =",first,"\nB =",second)

And it gives you:

$ python3 /tmp/tmp.py
A = [1, 2, 3, 4, 5, 6]
B = [10, 50, 8, 9, 16, 18]

Upvotes: 1

Will
Will

Reputation: 24699

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))

Upvotes: 2

Related Questions