【问题标题】:Check if an array is an element of another array python [duplicate]检查数组是否是另一个数组python的元素[重复]
【发布时间】:2021-08-16 14:26:48
【问题描述】:

我有一个 3d 点的 python 数组,例如 [p1,p2,...,pn] 其中 p1 = [x1,y1,zi] 我想检查天气特定点 p_i 是其中的成员,什么这是正确的方法吗?

这是我尝试过的代码

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)

但是我得到了错误

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

显然这种方法适用于字符串和数字,但不适用于数组。这样做的正确方法是什么?

【问题讨论】:

    标签: python arrays list numpy


    【解决方案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)
    

    【讨论】:

      【解决方案2】:

      尝试沿轴=1 使用all 并检查结果中的any 是否为True

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

      输出:

      [20  0 20]
      [5 5 5]
      

      【讨论】:

        【解决方案3】:

        试试下面的

        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)
        

        【讨论】:

        • 谢谢你的建议,你能告诉我这个到底是做什么的吗? . points: List[Point] = [] ?
        • @brownfox 我可以肯定地告诉你:-)。 List[Point] 是类型提示。它增加了代码的可读性,并被类型检查器使用。请参阅docs.python.org/3/library/typing.html BTW - 我认为这个解决方案更干净 - 它不需要任何外部库!
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-13
        • 2021-01-30
        • 2022-01-02
        • 2021-12-03
        • 2019-05-05
        相关资源
        最近更新 更多