eval ?
Mel Wilson
mwilson at the-wire.com
Fri Feb 20 09:46:23 EST 2004
In article <mailman.104.1077277571.27104.python-list at python.org>,
Angelo Secchi <secchi at sssup.it> wrote:
>
>I'm trying to use eval (is the right function? ) to generate empty lists
>with different names(es. list_1, list_2, list_3, ...) in a loop similar
>to:
>
>for index in range(1,4):
> list=[]
> for index in range(1,7):
> if <condition>:
> list.append(1)
> foo='list_'+str(index)+'=list'
> eval(foo)
>
>I am not a programmer as you probably see from the code and I do not
>even know if this is the right approach to do that in Python (I used
>this structure with Matlab that I want now to dismiss ...)
I believe you want exec . Do you mean something like:
for i in range (1, 4+1):
li = []
for j in range (1, 7+1):
if (condition):
li.append (1)
exec ("list_%d%d = li[:]" % (i, j,))
(I've improvised out of a few possible problems.
`list` is already used in Python as the type for lists.
It's better to name an actual list something else: `li` for
instance.
It's possible to use `index` for two different things, as
you've done, but frequently each use needs its own name, as
here.
Each run through the `i` loop creates a distinct list,
which is given the name `li`. In the `j` loop this distinct
list is appended to without changing its identity. Unless
you apply your new name to a copy of that list, all your
`list_1x` names will apply to the same list instance.. as will
all your `list_2x` names, all your `list_3x` names, etc. The
`li[:]` construct copies the contents of li into a fresh
list instance each time. This may (or may not) be what you
wanted.)
Regards. Mel.
More information about the Python-list
mailing list