-1

Say I have a list:

D = [str1, str2, str3, str4, str5, str6, ... str100]

And I want to search the list using [str4 str5] as my key word and return the index of the last element of my keyword. In this case, I want to return 4 since str5 is the last element in my keyword and its index in the searched list, i.e. D, is 4.

Is there any efficient way of doing this? I thought of using a for loop but that takes too much time, since I have a very big list. Is list comprehension a solution?

EDIT:

To answer Ben's question, I need to search [str4 str5] as a set because I want to make sure these two strings are together. It is possibly that [str5] can appear by itself in the future without str4 preceding it.

qiaop
  • 129
  • 3
  • 7
  • why not just search for `str5`? It's done by `D.index(str5)` – Ben Jul 18 '14 at 20:38
  • If you need fast lookups, you are using the wrong data structure. I think giving us more context will go a long way. – C.B. Jul 18 '14 at 20:38
  • Because I need to make sure str4 is right before str5. I want to search these two strings as a set. – qiaop Jul 18 '14 at 20:39
  • @C.B. I can't use a dict because I need duplicate keys. I also need the order. What's the best data structure? – qiaop Jul 18 '14 at 20:39
  • 2
    look up the index for `str4` similarly, and check if they are consecutive – Ben Jul 18 '14 at 20:39
  • @Ben Yes, I can look up str4 and check if the previous string is str5. Is there a more efficient way? I want to save some time. Thanks! – qiaop Jul 18 '14 at 20:42
  • "look up str5, see if str4 directly preceeds it", is still one search, a search you are thinking about doing anyway. – Ben Jul 18 '14 at 20:43
  • @Ben I guess so. Thanks! I was trying to find a more elegant way especially I'm a learner. Anyway, thank you! – qiaop Jul 18 '14 at 20:47
  • 1
    See [this question](http://stackoverflow.com/questions/2250633/python-find-a-list-within-members-of-another-listin-order) and [this one](http://stackoverflow.com/questions/425604/best-way-to-determine-if-a-sequence-is-in-another-sequence-in-python). – whereswalden Jul 18 '14 at 20:55

1 Answers1

-1

Determine if the first value is present, and then determine if the second value follows it. You will need to apply the logic you desire if the values are not present or the values are not present sequentially.

x = ['str4', 'str5']

if d.index(x[0]) + 1 == d.index(x[1]):
    return d.index(x[1])