Malcom.Z
Malcom.Z

Reputation: 3

Searching for a value in a two-dimensional python array

I'm looking to make a project I have to use a two-dimensional table, in this table I have to find precise values. In this short code I try to find the value 6 but I can't. Thank you in advance for your help

#!/usr/bin/python3
from math import *
import sys
bord = [[1, 2, 3], [4, 5, 6]]


def main():
    x = 0
    y = 0
    while(x < 2):
        while(y < 3):
            print(bord[x][y])
            if (bord[x][y] == 5):
                print("here")
            y = y + 1
        x = x + 1
main()

Upvotes: 0

Views: 52

Answers (2)

splash58
splash58

Reputation: 26153

The problem in your code that you have to init y not out the loops

bord = [[1, 2, 3], [4, 5, 6]]  

def main():
    x = 0

    while(x < 2):
        y = 0
        while(y < 3):
            if (bord[x][y] == 5):
                print("here")
            y = y + 1
        x = x + 1
main()

Now you loop only the first inner list

Upvotes: 1

Vassilios
Vassilios

Reputation: 493

def find_pos(bord, number):
  for list_num in enumerate(bord):
    if number in list_num[1]:
      return (list_num[0], list_num[1].index(number))

If you are looking for 6 then this function should return (1, 2) which means that your number is in the list with index 1 and at the position with index 1.

Upvotes: 0

Related Questions