How can I implement matlabs ``ismember()`` command in Python?

后端 未结 6 2309
星月不相逢
星月不相逢 2020-12-19 22:59

here is my problem: I would like to create a boolean matrix B that contains True everywhere that matrix A has a value contained in vector v. One inconvenient so

6条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-19 23:11

    I don't know much numpy, be here's a raw python one:

    >>> A = [[0,1,2], [1,2,3], [2,3,4]]
    >>> v = [1,2]
    >>> B = [map(lambda val: val in v, a) for a in A]
    >>>
    >>> B
    [[False, True, True], [True, True, False], [True, False, False]]
    

    Edit: As Brooks Moses notes and some simple timing seems to show, this one is probably be better:

    >>> B = [ [val in v for val in a] for a in A]
    

提交回复
热议问题