[Tutor] list.index() question
Robert Berman
bermanrl at cfl.rr.com
Thu Dec 8 23:23:12 CET 2011
On 12/08/2011 05:03 PM, Steven D'Aprano wrote:
> Robert Berman wrote:
>> Hi,
>>
>> Assuming a list similar to this: l1=[['a',1],['b',2],['c',3]] and I
>> want to get the index of 'c'.
>
> You will need to explain what you mean by "the index of 'c'".
>
> Do you mean 0, because 'c' is in position 0 of the sub-list ['c', 3]?
>
> Or do you mean 2, because 'c' is in the sub-list at position 2?
>
> What happens if there is a sub-list ['d', 'c']? Should that also
> count? What about sub-sub-lists, should they be checked too?
>
> Here is a version which checks each sub-list in turn, and returns the
> index of any 'c' it finds of the first such sub-list.
>
> def inner_find(list_of_lists):
> for sublist in list_of_lists:
> try:
> return sublist.index('c')
> except ValueError:
> pass # go to the next one
> # If not found at all:
> raise ValueError('not found')
>
>
> Here's a version which finds the index of the first sub-list that
> begins with 'c' as the zeroth element:
>
> def match_sublist(list_of_lists):
> for i, sublist in enumerate(list_of_lists):
> if sublist and sublist[0] == 'c':
> return i
> raise ValueError('not found')
>
>
>
>
> Other variations on these two techniques are left for you to
> experiment with.
>
>
>
Thank you Steven and Joel. You have given me information to experiment
with which is most appreciated.
Robert
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20111208/917e15b1/attachment.html>
More information about the Tutor
mailing list