Spikey Cakey
Spikey Cakey

Reputation: 7

2D Array in Python

I am very new to 2D Arrays in python. I am trying to create a 2D array that asks the user to input a name and then finds the name in the array and prints out what position that name is.

My code so far is:

pupil_name = [['Jess', 0], ['Tom', 1], ['Erik', 2]]

enter_pupil = input('Enter name of Pupil   ')  
print(str(pupil_name) + ' is sitting on chair number ' + str([]))

print(' ')

Is what I am asking possible? It is just for fun and would love to make it work. Thanks in advance

Upvotes: 0

Views: 302

Answers (4)

Hai Vu
Hai Vu

Reputation: 40773

You should use a dictionary, as others pointed out. However, if you still want to keep a 2D list, here is what you can do:

pupil_name = [['Jess', 0], ['Tom', 1], ['Erik', 2]]
enter_pupil = input('Enter name of Pupil   ')

for pupil, seat in pupil_name:
    if pupil == enter_pupil:
        print('{} is seating at chair number {}'.format(pupil, seat))
        break
else:
    print('Not found: {}'.format(enter_pupil))

Notes

  • The code loops through pupil_name and each iteration assigned the sub list to pupil and seat.
  • If we found a match, we print out the name and seat and break out of the loop. There is no point to keep looping since we found what we want.
  • The else clause is an interesting and unique aspect of Python for loop: if we loop through all names/seats and did not break (i.e. did not find the name), then the code under the else clause is executed.

Upvotes: 2

noslenkwah
noslenkwah

Reputation: 1744

Here's a solution that uses your nested lists. See Jim Wright's answer for a dict solution.

pupil_name = [['Jess', 0], ['Tom', 1], ['Erik', 2]]

def find_chair(name, chair_numbers):
    for (n, c) in chair_numbers:
        if n == name:
            return c
    return None

enter_pupil = input('Enter name of Pupil   ')  
print(str(enter_pupil) + ' is sitting on chair number ' + str(find_chair(enter_pupil, pupil_name)))

print(' ')

Upvotes: 0

Jim Wright
Jim Wright

Reputation: 6058

As others have advised in comments you should use a dict.

You should also be using raw_input instead of input as it converts the user input to a str.

student_chair_numbers = {
    'Jess': 0,
    'Tom': 1,
    'Erik': 2,
}
enter_pupil = raw_input('Enter name of Pupil   ')
print(enter_pupil + ' is sitting on chair number ' + str(student_chair_numbers[enter_pupil]))

Upvotes: 0

timgeb
timgeb

Reputation: 78780

You want a dictionary.

>>> pupil_name = [['Jess', 0], ['Tom', 1], ['Erik', 2]]
>>> pupil_pos = dict(pupil_name)
>>> 
>>> pupil_pos
{'Jess': 0, 'Erik': 2, 'Tom': 1}
>>> pupil_pos['Erik']
2

This gives you a mapping of names to positions, which you can query by providing the name.

Upvotes: 0

Related Questions