python(or numpy) equivalent of match in R

后端 未结 1 1515
北海茫月
北海茫月 2020-12-11 01:48

Is there any easy way in python to accomplish what the match function does in R? what match in R does is that it returns a vector of the positions of (first) matches of its

相关标签:
1条回答
  • 2020-12-11 02:20
    >>> a = [5,4,3,2,1]
    >>> b = [2,3]
    >>> [ b.index(x) if x in b else None for x in a ]
    [None, None, 1, 0, None]
    

    Add 1 if you really need position "one based" instead of "zero based".

    >>> [ b.index(x)+1 if x in b else None for x in a ]
    [None, None, 2, 1, None]
    

    You can make this one-liner reusable if you are going to repeat it a lot:

    >>> match = lambda a, b: [ b.index(x)+1 if x in b else None for x in a ]
    >>> match
    <function <lambda> at 0x04E77B70>
    >>> match(a, b)
    [None, None, 2, 1, None]
    
    0 讨论(0)
提交回复
热议问题