Onca
Onca

Reputation: 1135

Python hash structure

I get as an input N*M matrix (tuple of tuples), values from 1 to 9.

What is the best way to hash this structure, so I can get the place (x,y) of every 8 value? (8 for example, can be 5 or 7...)

Upvotes: 1

Views: 142

Answers (3)

unutbu
unutbu

Reputation: 880627

Since you want to find the location of 5s and 7s and 8s, it may be more efficient to store all the locations in a dict with one pass through the matrix, instead of one pass for the 5s, one pass for the 7s, etc...

loc = {}    
for x in range(N):
    for y in range(M):
        loc.setdefault(matrix[x][y], []).append((x,y))

Upvotes: 3

FogleBird
FogleBird

Reputation: 76842

"Hash" is the wrong word for this. You just want to search a 2D array for a particular value. Maybe something like this...

height = len(data)
width = len(data[0])
eights = [(x, y) for y in range(height) for x in range(width) if data[x][y] == 8]

Upvotes: 1

John La Rooy
John La Rooy

Reputation: 304413

[(x,y) for x in range(N) for y in range(M) if matrix[x][y] == 8]

Upvotes: 0

Related Questions