Home > database >  How to Precisely Compare Values In a Nested For Loop
How to Precisely Compare Values In a Nested For Loop

Time:07-02

I'm trying to compare the values from a two dimensional arrays within a nested for loop and I can't seem to get the right relational operation in this situation.

So I'm looping through two dimensional arrays and comparing its values to values in another one dimensional array and I'm having a really interesting day.

import numpy as np

packetsDb = np.empty((0,4))

head = [['AAA', 'BBB', 'CCC', 'DDD']]
packet1 = [[255, 256, 257, 258]]
packet2 = [[255, 256, 257, 259]]
test = [255, 256, 257, 259]


packetsDb = np.append(packetsDb, np.array(head), axis=0)
packetsDb = np.append(packetsDb, np.array(packet1), axis=0)
packetsDb = np.append(packetsDb, np.array(packet2), axis=0)

for x in packetsDb:
   for y in x:
       print(test[0], y, test[0] == y)

//Result
255 AAA False
255 BBB False
255 CCC False
255 DDD False
255 255 False //Whats happening here
255 256 False
255 257 False
255 258 False
255 255 False //and here
255 256 False
255 257 False
255 259 False

CodePudding user response:

The result is indeed counter-intuitive at first, but it gets clearer once you print the types as well:

for x in packetsDb:
    for y in x:
        print(test[0], y, test[0] == y, type(test[0]), type(y))

//Result
255 AAA False <class 'int'> <class 'numpy.str_'>
...

test[0] and y look the same when printed, but they are in fact different types and thus the comparison resolves to False.

When you did append the string-list to the numpy-array numpy did cast the full array to a str-type including the integers to be able to represent the new data. See this link as a reference Python - strings and integers in Numpy array

  • Related