Mariam
Mariam

Reputation: 1

How to read columns from a file and add each column in separate lists in python 3.4

I need dynamic code:

if the file data looks like below, then how can I add each column of it in 3 list separately in python 3.4.1?

0 4 5

1 0 0

1 56 96

I tried and read the data from file and stored it in a list like: scores = [['0','4', '5'],['1','0','0], ['1', '56','96']]. but now I don't know how write the code to put each first letter of this array to 3 separate lists or arrays. like: list1 = [0, 1,1], list2 = [4,0,56] and list3 = [5,0,96]

thanks

Upvotes: 0

Views: 135

Answers (1)

Thibaut
Thibaut

Reputation: 1408

Basically, you have a list of the rows, and you want a list of the columns. This is called transposing and can be written very concisely in Python like this:

columns = zip(*scores)

After doing this, columns[0] will contain the first column, columns[1] the second column, and so on. The columns will be tuples. If you really need lists you can apply the list function to the result:

columns = map(list, zip(*scores))

This dark-magic-looking syntax first uses the * operator which unpacks a list of arguments. Here this means that zip(*scores) is equivalent to:

zip(['0','4', '5'], ['1','0','0'], ['1', '56','96'])

Note how each element of the scores list is now a different argument of the zip function. Then we use the zip function.

Upvotes: 2

Related Questions