Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #4264
| Newsgroups | comp.lang.python |
|---|---|
| References | <4DB8B7F6.9040500@sonic.net> <mailman.917.1303951783.9059.python-list@python.org> |
| Subject | Re: use of index (beginner's question) |
| From | "Rhodri James" <rhodri@wildebst.demon.co.uk> |
| Message-ID | <op.vun167mqa8ncjz@gnudebst> (permalink) |
| Organization | virginmedia.com |
| Date | 2011-04-28 22:05 +0100 |
On Thu, 28 Apr 2011 01:49:33 +0100, Chris Angelico <rosuav@gmail.com>
wrote:
> On Thu, Apr 28, 2011 at 10:42 AM, Rusty Scalf <iai-gis@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
Back to comp.lang.python | Previous | Next — Previous in thread | Find similar
Re: use of index (beginner's question) Chris Angelico <rosuav@gmail.com> - 2011-04-28 10:49 +1000
Re: use of index (beginner's question) Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2011-04-28 03:23 +0200
Re: use of index (beginner's question) Chris Rebert <clp2@rebertia.com> - 2011-04-27 18:39 -0700
Re: use of index (beginner's question) Chris Angelico <rosuav@gmail.com> - 2011-04-28 11:45 +1000
Re: use of index (beginner's question) Iain King <iainking@gmail.com> - 2011-04-28 01:13 -0700
Re: use of index (beginner's question) Algis Kabaila <akabaila@pcug.org.au> - 2011-04-28 13:32 +1000
Re: use of index (beginner's question) Graeme Glass <graemeglass@gmail.com> - 2011-04-28 02:26 -0700
Re: use of index (beginner's question) "Rhodri James" <rhodri@wildebst.demon.co.uk> - 2011-04-28 22:05 +0100
csiph-web