Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/70.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python(或numpy)等价于R中的match_Python_R_Numpy - Fatal编程技术网

python(或numpy)等价于R中的match

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

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) 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]