Home > Blockchain >  Using an Input to Retrieve a Corresponding Element From a 2D Array
Using an Input to Retrieve a Corresponding Element From a 2D Array

Time:11-27

This might be a really obvious solution to some, but, being pretty new to python, I'm unsure how to do it - In short, I want to take a user's input, and find the corresponding element on a 2D array, i.e. an input of '1' would print 'a', '2' would print 'b', and so on. Is there a way to do this? The code I've written so far is below

var=[["1","a"],["2","b"],["3","c"]]
inp='x'
while inp!='1' and inp!='2' and inp!='3':
  inp=str(input("Enter a number 1-3\n"))

I've not got a clue what to try, and I'm yet to find a solution - that just might be due to my poor phrasing though - so any help is greatly appreciated!

CodePudding user response:

Loop through the sub-lists inside var until you find one where the first element matches the user input. Then print the second element of that sub-list.

for sublist in var:
    if sublist[0] == inp:
        print(sublist[1])

CodePudding user response:

There are a lot of ways of doing what you want to do. Here's a way that is easier for a beginner to understand (hopefully):

var=[["1","a"],["2","b"],["3","c"]]
inp='x'
while inp!='1' and inp!='2' and inp!='3':
  inp=input("Enter a number 1-3\n")

for entry in var:
    if entry[0] == inp:
        print(entry[1])
        break

Note that I removed the call to str() that you had put around your call to input(), as that function already returns a string value.

A better way to do this if you can choose the form of your input data structure is to use a map rather than a list. Here's how to do that. Note how much simpler the added code becomes:

var= {'1': 'a', '2': 'b', '3': 'c'}
inp='x'
while inp!='1' and inp!='2' and inp!='3':
  inp=input("Enter a number 1-3\n")

print(var[inp])

CodePudding user response:

One of the simplest pythonic ways to do this would be this: Note that your question is relatively easy, and that therefore are many answers possible

var=[["1","a"],["2","b"],["3","c"]]

inp = '1'

def function(lst, inp):
    for val in lst:
        if val[0] == inp:
            return val[1]
        
function(var, inp)
  • Related