wildcard match with list.index()

Sion Arrowsmith siona at chiark.greenend.org.uk
Wed Nov 19 07:19:39 EST 2008


jeff  <jeffreykr at gmail.com> wrote:
>>>> list
>[['a', [], []], ['b', [1, 2], []], ['c', [3, 4], [5, 6]]]
>>>> list.index(['b',[],[]])
>
>ie, would like to match the second element in the list with something
>where i just know 'b' is the first element, but have no idea what the
>other elements will be:
>
>Traceback (most recent call last):
>  File "<stdin>", line 1, in <module>
>ValueError: list.index(x): x not in list
>>>> list.index(['b',[1,2],[]])
>1

If you really want to do that:

py> lst.index([x for x in lst if x[0] == 'b'][0])

(Oh, yeah, don't shadow the builtin "list".)

What I suspect would be far more useful is a better data structure:

py> dct = dict((x[0], x[1:]) for x in lst)
py> dct['b']>>> dct['b']
[[1, 2], []]

Dealing with the case of more than one entry identified by 'b' is
left as a problem to someone who knows what the data actually is.

-- 
\S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/
   "Frankly I have no feelings towards penguins one way or the other"
        -- Arthur C. Clarke
   her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump



More information about the Python-list mailing list