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

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I have tried zip but it says "zip object at 0x10291fb08> and whle trying map it says"map object at 0x102a1b668>.
Oh, this is because you are using Python 3.x and not Python 2.x. In this case try: columns = list(zip(*scores))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.