本文介绍了R中匹配的python(或numpy)等效项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在python中,有什么简单的方法可以完成R函数中的match函数?R中的match所执行的操作是返回其第一个参数在其第二个参数中(第一个)匹配位置的向量.
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 first argument in its second.
例如,以下R代码段.
For example, the following R snippet.
> a <- c(5,4,3,2,1)
> b <- c(2,3)
> match(a,b)
[1] NA NA 2 1 NA
在python中进行翻译,我正在寻找的是执行以下操作的函数
Translate that in python, what I am looking for is a function that does the following
>>> a = [5,4,3,2,1]
>>> b = [2,3]
>>> match(a,b)
[None, None, 2, 1, None]
谢谢!
推荐答案
>>> 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.
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]
这篇关于R中匹配的python(或numpy)等效项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!