python(或numpy)等价于R中的match
python中有没有简单的方法来完成match函数在R中的功能? R中的匹配所做的是,它返回其第一个参数在第二个参数中的(第一个)匹配位置向量 例如,下面的R代码段python(或numpy)等价于R中的match,python,r,numpy,Python,R,Numpy,python中有没有简单的方法来完成match函数在R中的功能? R中的匹配所做的是,它返回其第一个参数在第二个参数中的(第一个)匹配位置向量 例如,下面的R代码段 > a <- c(5,4,3,2,1) > b <- c(2,3) > match(a,b) [1] NA NA 2 1 NA 谢谢大家! >>> a = [5,4,3,2,1] >>> b = [2,3] >>> [ b.index(x) i
> a <- c(5,4,3,2,1)
> b <- c(2,3)
> match(a,b)
[1] NA NA 2 1 NA
谢谢大家!
>>> 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]
如果你真的需要位置“基于一”而不是“基于零”,请添加1
如果您打算大量重复此单行程序,则可以使其可重复使用:
>>> 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]
match=lambda,b:[b.索引(x)+1如果b中的x,则b中的x没有]
>>>匹配
>>>比赛(a,b)
[无,无,2,1,无]
不错。当元素不存在时,这是绕过list.index()错误的好方法。
>>> [ b.index(x)+1 if x in b else None for x in a ]
[None, None, 2, 1, None]
>>> 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]