0

R has a match() function, for example:

a=c(1,2,3,4,5)
b=c(1,2,6)
match(b,a,nomatch=-1) #find index of b values in a

Index values in R are 1-based, so the match() call above will output:

1  2 -1

What's the equivalent function or the best way to implement it in Python ? Thanks in advance.

b_yang
  • 109
  • 6
  • Have look [here](http://stackoverflow.com/questions/4110059/pythonor-numpy-equivalent-of-match-in-r) – Marcin Feb 24 '15 at 01:18
  • Hi Marcin, I don't have enough reputation to comment on the other question, so I'll ask the follow-up question here. The solution provided is: `[ b.index(x) if x in b else None for x in a ]` However is it efficient ? Does it sort or hash b for every item in a ? – b_yang Feb 24 '15 at 02:24
  • No sorting involved and the comparison is done by value as you deal only with integers. So I would say its efficient. But is it optimal? I dont know. – Marcin Feb 24 '15 at 02:34
  • So it's doing a linear scan ? Not sorting b and then binary search ? – b_yang Feb 24 '15 at 02:52
  • Yep. `x in b` is O(n). More here about list and complexity of operations on list elements [here](https://wiki.python.org/moin/TimeComplexity) – Marcin Feb 24 '15 at 03:03

0 Answers0