Numpy.Array in Python list?

前端 未结 5 1410
[愿得一人]
[愿得一人] 2020-12-01 18:42

I\'ve got a list (used as a stack) of numpy arrays. Now I want to check if an array is already in the list. Had it been tuples for instance, I would simply have written some

相关标签:
5条回答
  • 2020-12-01 19:02

    What about this:

    a = array([1, 1])
    
    l = [np.array([1,1]), np.array([2,2])]
    list(map(lambda x: np.array_equal(x, a), l)
    
    [True, False]
    
    0 讨论(0)
  • 2020-12-01 19:02

    You can convert the array into a list by using tolist() and then do the check:

    my_list = [[1,1], [2,2]]
    
    print(np.array([1,1]).tolist() in my_list)
    print(np.array([1,2]).tolist() in my_list)
    
    0 讨论(0)
  • 2020-12-01 19:11

    To test if an array equal to a is contained in the list my_list, use

    any((a == x).all() for x in my_list)
    
    0 讨论(0)
  • 2020-12-01 19:13

    Sven's answer is the right choice if you want to compare the actual content of the arrays. If you only want to check if the same instance is contained in the list you can use

    any(a is x for x in mylist)
    

    One benefit is that this will work for all kinds of objects.

    0 讨论(0)
  • 2020-12-01 19:15

    If you are looking for the exact same instance of an array in the stack regardless of whether the data is the same, then you need to this:

    id(a) in map(id, my_list)
    
    0 讨论(0)
提交回复
热议问题