[Tutor] Enter mode where you can input list indices
Alan Gauld
alan.gauld at yahoo.co.uk
Sun Oct 17 04:31:07 EDT 2021
On 16/10/2021 16:20, Julius Hamilton wrote:
> Hey,
>
> I would like to explore the contents of a list where I could just enter a
> mode where any index I type in, it would print the value for some list,
> like this:
>
>>>> p()
> 1
> ["apple", "cat"]
> 1 2
> cat
> 3
> Index out of bounds
You might want to look at the cmd module which provides a
framework for building interpreter like prompts into your program.
> def p():
> n = input()
n is probably a bad name. index_str or similar
would be more descriptive.
> while n != "":
>
> After the input is received it must be parsed into a list of integers:
> n = n.split(' ')
> indices = []
> for item in n:
> indices.append(int(item))
This is basically a list comprehension:
indices = [int(item) for item in n]
> indices. Next, index the list (in the enclosing scope) by however many
> indices there are:
>
> for i in indices:
> list = list[i]
This is the more challenging part, you probably want
to pass the list into the function. Or if you want to
use a different list for each iteration you would pass
a list of lists. In that ase your input() should
include a prompt describing which list is to be indexed.
Something like:
lists=(("list1",lst1),("list2",lst2,....)
def p(lists):
for List in lists:
index_str = input("type list of indices for %s"%List[0]
while index_str != "":
...
for n in indices:
print(List[1][n]
...
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list