On Thu, 28 Apr 2011 01:49:33 +0100, Chris Angelico <ros...@gmail.com>
wrote:

On Thu, Apr 28, 2011 at 10:42 AM, Rusty Scalf <iai-...@sonic.net> wrote:
list1 = ['pig', 'horse', 'moose']
list2 =  ['62327', '49123', '79115']
n = 2
s2 = "list" + `n`
a = s2[list1.index('horse')]
print a

s2 is a string with the value "list2"; this is not the same as the
variable list2. You could use eval to convert it, but you'd do better
to have a list of lists:

lists = [
 ['pig', 'horse', 'moose']
 ['62327', '49123', '79115']
]

Then you could use:
n = 2
a = lists[n][list1.index('horse')]

*cough* I think you mean

n = 1
a = lists[n][list[0].index('horse')]

The alternative would be to have a dictionary of lists:

lists = {
    "list1": ['pig', 'horse', 'moose'],
    "list2": ['62327', '49123', '79115']
}

n = 2
s2 = "list" + str(n)
a = lists[s2][lists["list1"].index('horse')]

Both of these can be made less ugly if the list you want to index into
isn't one of the lists you might want to look up, but that's just a detail.

--
Rhodri James *-* Wildebeest Herder to the Masses
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to