2

I have a python array of 3d points such as [p1,p2,...,pn] where p1 = [x1,y1,zi] I want to check weather a particular point p_i is a member of this, what is the right method for this?

Here is the code which I tried

import numpy
my_list = []
for x in range(0,10):
    for y in range(0,10):
        for z  in range(0,5):
            p1 = numpy.array([x,y,z])
            my_list.append(p1)

check_list = numpy.array([[1,2,3],[20,0,20],[5,5,5]])
for p in check_list :
    if p not in my_list:
        print (p)

However I;m getting the error

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

Apparently this method works for strings and numbers but not for arrays. What is the correct way to do this?

brownser
  • 545
  • 7
  • 25

3 Answers3

1

Try using all along axis=1 and check if any of the result is True:

for p in check_list:
    if not (p==my_list).all(1).any():
        print(p)

Output:

[20  0 20]
[5 5 5]
not_speshal
  • 22,093
  • 2
  • 15
  • 30
1
import numpy

my_list = []
for x in range(0, 10):
    for y in range(0, 10):
        for z in range(0, 5):
            p1 = numpy.array([x, y, z])
            my_list.append(p1)

check_list = numpy.array([[1, 2, 3], [20, 0, 20], [5, 5, 5]])
for p in check_list:
    if not numpy.any(numpy.all(p == my_list, axis=1)):
        print(p)
S P Sharan
  • 1,101
  • 9
  • 18
1

Give the below a try

from dataclasses import dataclass
from typing import List


@dataclass
class Point:
    x: int
    y: int
    z: int


points: List[Point] = []
for x in range(0, 10):
    for y in range(0, 10):
        for z in range(0, 5):
            points.append(Point(x, y, z))
print(Point(1, 2, 3) in points)
print(Point(1, 2, 3888) in points)
balderman
  • 22,927
  • 7
  • 34
  • 52
  • Thank you for the suggestion, can you please tell me what exactly this one is doing? . `points: List[Point] = []` ? – brownser Aug 16 '21 at 14:43
  • @brownfox I can tell you for sure :-). `List[Point]` is type hint. It increase the readability of the code and is used by type checkers. see https://docs.python.org/3/library/typing.html BTW - I think this solution is cleaner - it does not require any external lib! – balderman Aug 16 '21 at 14:46