选择与另一个列表相交的列表元素的简单方法?(Python)

gen*_*ser 2 python

在 R 中,如果我希望x其中的所有元素都在 中y,我会这样做

x[x %in% y]
Run Code Online (Sandbox Code Playgroud)

在 python 中,我可以使用列表理解:

[i for i in y if i in x]
Run Code Online (Sandbox Code Playgroud)

有没有更干净/更可读的方式?我正在掌握 python 的窍门,但我正在编写的代码的可读性并不像我习惯的那样。我尝试的第一件事没有成功:

x[x in y]
Run Code Online (Sandbox Code Playgroud)

我猜是因为inpython 中只接受标量。

jpp*_*jpp 5

你是对的:Python 操作默认情况下不是矢量化的。在这方面,R 比常规 Python 更接近第 3 方Pandas的 API 。所以你可以使用 Pandas 系列对象:

import pandas as pd

x = pd.Series([1, 2, 3, 4])
y = pd.Series([2, 4, 6, 8])

res = x[x.isin(y)]

print(res)  # output Pandas series
# 1    2
# 3    4
# dtype: int64

print(res.values)  # output NumPy array representation
# array([2, 4], dtype=int64)
Run Code Online (Sandbox Code Playgroud)

Pandas 构建于NumPy之上,因此毫不奇怪,您可以在 NumPy 中执行相同的操作:

import numpy as np

x = np.array([1, 2, 3, 4])
y = np.array([2, 4, 6, 8])

res = x[np.isin(x, y)]

print(res)
# array([2, 4])
Run Code Online (Sandbox Code Playgroud)