accessing elements in multi-dimensional sequences

Anton Vredegoor anton at vredegoor.doge.nl
Fri May 28 07:58:23 EDT 2004


Rodrigo Daunaravicius <rodelrod at hotmail.com> wrote:

>Is there an elegant way to directly refer the 2nd dimension of a
>multi-dimensional sequence (like the nth character in a list of strings).
>An example would be deleting the newline in all the strings from a list
>obtained through readlines without recurring to 'for' loops.

d =  ['0891931243\n', '0325443777\n', '0933477028\n',
'0699624617\n', '0922210996\n']

#swap rows and columns, with the side effect of turning
#strings into lists, strings must be of equal length or
#else some information will be lost:

d1 = zip(*d)

#remove a row (corresponds to a *column* in the old view)
#this is an elementary operation now:

del d1[-1]

#swapping again restores the old row and column view:

d1 = zip(*d1)

#join the elements of the sublists in order to produce strings:

d1 = map(''.join,d1)

print d1

#output is:
#['0891931243', '0325443777', '0933477028', '0699624617',
#'0922210996']


While this way of coding enables one to *think* about the problem more
efficiently it is not necessarily the most efficient algorithm for
accomplishing this specific effect. If it's fast enough however, why
not reduce ones mental computing cycles and let the computer do all
the leg work?

It might even ameliorate entropy problems later on in the evolution of
the universe since the operations could probably be reversed more
efficiently even if the computer moves more electrons through the
silicon?

Anton




More information about the Python-list mailing list