problem about list indexing

hollowspook hollowspook at gmail.com
Sun Nov 26 05:38:52 EST 2006


Thanks, John

how about indexing 1-7, 10
[range(1:8),10] will generate [[1, 2, 3, 4, 5, 6, 7], 10], instead of
[1, 2, 3, 4, 5, 6, 7, 10]


"John Machin 写道:
"
> hollowspook wrote:
> > Hi, there
> >
> > a = range(100)
> >
> > if I want to use No 7, 11, 56,90 in a, then the only way I do is [a[7],
> > a[11], a[56], a[90]].
> > Is there any other way?
> >
>
> I presume a = range(100) is just an indication that a is a list -- the
> literal answer to your question as asked is simply [7, 11, 56, 90]
>
> In the general case that a is *any* list (or anything else that
> supports the index protocol, e.g. a string, a tuple, an array.array
> instance, or some instance of a so-written class), you can use a "list
> comprehension". Example:
>
> | >>> a = 'qwertyuiopasdfghjklzxcvbnm'
> | >>> [a[x] for x in [25, 0, 13, 1]]
> | ['m', 'q', 'f', 'w']
>
> Do try and find "list comprehension" in the manual and in your book or
> tutorial. It's useful for much more than the above.
> 
> HTH,
> John




More information about the Python-list mailing list