简体   繁体   中英

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

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 (ie did not find the name), then the code under the else clause is executed.

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.

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]))

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(' ')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM