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

2024-03-29 06:46:46 发布

您现在位置:Python中文网/ 问答频道 /正文

在R中,如果我想要xy的所有元素,我会这样做

x[x %in% y]

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

[i for i in y if i in x]

有没有更清晰/更易读的方法?我已经掌握了python的窍门,但是我编写的代码并不像我习惯的那样可读。我尝试的第一件事没有成功:

x[x in y]

我猜是因为in在python中只接受标量。你知道吗


Tags: 方法代码in元素列表forif标量
3条回答

通过定义customgetitem()方法,可以创建一个MyList类型,该类型将具有所需的行为

from collections import UserList, Iterable

class MyList(UserList):
    def __getitem__(self, item):
        if isinstance(item, Iterable):
            return MyList(x for x in self.data if x in item)
        return super(MyList, self).__getitem__(item)


if __name__ == '__main__':
    l = MyList([1, 2, 3, 4, 5])
    v = l[[2, 3, 11]]
    print(v)  # [2, 3]

这些问题已在此处解决: Filter dataframe rows if value in column is in a set list of values

下面是一个使用.isin()方法的示例,相当于R的%in%。你知道吗

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

>> x[x.isin(y)]

0    1
2    3
4    5

您是正确的:默认情况下,Python操作不是矢量化的。在这方面,R比常规Python更接近于第三方Pandas的API。因此可以使用熊猫系列对象:

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)

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

相关问题 更多 >