Newbie Q: Adding String to list

Hans Aschauer Hans.Aschauer at Physik.uni-muenchen.de
Thu Aug 1 04:37:41 EDT 2002


DP wrote:

> Newbie questions - I'm trying to improve my skills by trying to code more
> efficiently, and all help will be appreciated.
> 
> I have an array
> AA = ["a","b","c"]
> 
> I'd like to add text, let's say
> x = "x"
> 
> to each element of the array, to get
> AAx = ["xa","xb","xc"]

AAx = [ 'x' + i for i in AA]

> What's the simplest way to accomplish this?
> I'd like to avoid looping over AA.

This is called 'list comprehension'. Have a look at the tutorial, it is 
explained there. Please note that a recent python (python >= 2.1(?)) is 
required, however.
 
> And if
> X = ["x","y","z"]
> 
> what's the best way to generate (the equivalent of)
> AAXX = |"xa","xb","xc"|
>        |"ya","yb","yc"|
>        |"za","zb","zc"|
> 
> or
> AAX = ["xa","xb","xc","ya","yb","yc","za","zb","zc"]

AAX = [i+j for i in X for j in AA]

> OR
> if I have an array with N elements, what's the best way to convert this
> into a 2 dimensional array with (n X m) elements, where n*m = N. And vice
> versa.

n = 3
m = 2
a = [1,2,3,4,5,6]
M = [ a[n*i:n*(i+1)] for i in range(m)]

and back again:

aa = [i  for b in M for i in b]

> I need to be able to do this with numeric data too, but I should be able
> to figure that out from any hints I receive from above.

For heavy numeric stuff I would recommend using the "Numerical Python" 
library or similar (however, for my numeric stuff standart python is 
enough...)

Hans



More information about the Python-list mailing list