I want to ask the user which list they would like to access, then retrieve that list. I dont really have any code for this, because I'm currently just brainstorming. I couldn't really find a proper answer so here is a sample code I just made for the sake of explaining what I'm trying to do:
list1=[1, 2, 3, 4, 5]
list2=[6, 7, 8, 9, 10]
list3=['s', 'r', 't', 'd']
user_input=input('which list do you want to access')
I know that I can use if and elseif statements but the code I plan on making will have a large number of lists and I want a more efficient way to achieve this.
CodePudding user response:
You can use dictionary to map input string to the right list
list1=[1, 2, 3, 4, 5]
list2=[6, 7, 8, 9, 10]
list3=['s', 'r', 't', 'd']
lists = {
'list1': list1,
'list2': list2,
'list3': list3
}
user_input=input('which list do you want to access: ')
if user_input in lists:
print('selected list:', lists[user_input])
else:
print('no list matched')
CodePudding user response:
You can either use a nested list and access the lists by their index, or as already mentioned by @tax evader, use a dictionary to map the name of the list to the list itself:
# Using a list
def retrieve_list() -> list:
lists = [
[1, 2, 3, 4, 5]
[6, 7, 8, 9, 10],
['s', 'r', 't', 'd']
]
user_input = input("Which list do you want to access? ")
try:
return lists[int(user_input)-1]
except:
return None
# Using a dictionary
def retrieve_list() -> list:
lists = {
"1": [1, 2, 3, 4, 5]
"2": [6, 7, 8, 9, 10],
"3": ['s', 'r', 't', 'd']
}
user_input = input("Which list do you want to access? ")
return lists.get(user_input, None)