简体   繁体   中英

An equivalent to R's %in% operator in Python

I'm starting to learn a bit more about Python. One function I often want but don't know how to program/do in Python is the x %in% y operator in R. It works like so:

1:3 %in% 2:4

##[1] FALSE  TRUE  TRUE

The first element in x (1) has no match in y so FALSE where as the last two elements of x (2 & 3) do have a match in y so they get TRUE .

Not that I expected this to work as it wouldn't have worked in R either but using == in Python I get:

[1, 2, 3] == [2, 3, 4]
# False

How could I get the same type of operator in Python? I'm not tied to base Python if such an operator already exists elsewhere.

It's actually very simple.

if/for element in list-like object. 

Specifically, when doing so for a list it will compare every element in that list. When using a dict as the list-like object (iterable), it will use the dict keys as the object to iterate through.

Cheers

Edit: For your case you should make use of "List Comprehensions".

[True for element in list1 if element in list2]

%in% is simply in in Python. But, like most other things in Python outside numpy, it's not vectorised:

In [1]: 1 in [1, 2, 3]
Out[1]: True

In [2]: [1, 2] in [1, 2, 3]
Out[2]: False

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM