0

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

Thibaut
  • 1,398
  • 10
  • 16
Mariam
  • 1
  • This question has already been answered [here][1]. [1]: http://stackoverflow.com/questions/18713321/element-wise-addition-of-2-lists-in-python – Ed Doxtator Nov 13 '14 at 03:58

1 Answers1

2

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.

Thibaut
  • 1,398
  • 10
  • 16
  • I have tried zip but it says "zip object at 0x10291fb08> and whle trying map it says"map object at 0x102a1b668>. – Mariam Nov 13 '14 at 06:11
  • Oh, this is because you are using Python 3.x and not Python 2.x. In this case try: `columns = list(zip(*scores))` – Thibaut Nov 13 '14 at 06:27