[Tutor] something relevant to array

Andreas Perstinger andreas.perstinger at gmx.net
Fri Dec 23 13:19:45 CET 2011


On 2011-12-23 12:02, lina wrote:
>      for i in range(len(result)):
>          for j in range(len(result[i])):
>              print(result[i][j])
>
> still have a little problem about print out,
>
> I wish to get like
> a a
> b b
> c c
> which will show in the same line,
>
> not as
> a
> b
> c
> a
> b
> c

So you wish to print all the first elements from your sublists on the 
first line, all the second elements on the second line, and so on, right?

Python 3.2 (r32:88445, Mar 25 2011, 19:28:28)
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
 >>> result = [["a1", "b1", "c1"],["a2", "b2", "c2"],["a3", "b3", "c3"]]
 >>> for i in zip(*result):
...   print(" ".join(i))
...
a1 a2 a3
b1 b2 b3
c1 c2 c3

Explanation:
"zip()" takes an arbitrary number of iterables and "returns an iterator 
of tuples, where the i-th tuple contains the i-th element from each of 
the argument sequences or iterables." (see the docs on 
http://docs.python.org/py3k/library/functions.html#zip):

 >>> print(list(zip([1, 2, 3], [4, 5, 6])))
[(1, 4), (2, 5), (3, 6)]

In your case, you would have to call "zip()" with

zip(result[0], result[1], result[2], ... result[x])

depending on how many files you process.

But using the *-operator you can unpack "result" (which is a list of 
sublists), so that "zip" will see all the sublists as separate 
arguments. See also 
http://docs.python.org/py3k/tutorial/controlflow.html#unpacking-argument-lists 


For printing you just join all the elements of one tuple to a string.

HTH, Andreas


More information about the Tutor mailing list