Reputation: 131
I have seven lists from A to G. I read in an input n
, for example: b1
. What is the fastest way to print item at index 1
in list B
?
I have already tried this but it seems too long:
n = input()
if n[0].upper == 'A':
print(A[n[1]])
elif n[0].upper == 'B':
print(B[n[1]])
elif n[0].upper == 'C':
print(C[n[1]])
and so on ....
Is there any other way of doing this? And yeah this doesn't work:
print(n[0].upper()[n[1]])
Upvotes: 3
Views: 98
Reputation: 17612
You can use the built-in globals()
method of python. Try this:
A = [1, 2, 3, 4, 5]
B = [10, 20, 30, 40, 50]
C = [100, 200, 300, 400, 500]
D = [1000, 2000, 3000, 4000, 5000]
n = input()
n, i = n[0].upper(), int(n[1])
print(globals()[n][i])
If your variables are local to a function or any other scope, you can use the little brother of globals()
which is locals()
. Like so:
print(locals()[n][i])
By the way, you said position, but you are using as index. Definitely item at position 1 is at index 0. You may want to clarify that bit a little more. :)
Upvotes: 1
Reputation: 1902
if you want to minimize the nr of lines to print, you can store the lists in a dictionary. Looks like you know the list indices wont exceed 10, else n[1] wont be sufficient
>>> my_dict = {}
>>>
>>> a = [1,2,3]
>>> b = [4,5,6]
>>> c = [7,8,9]
>>>
>>> my_dict['a'] = a
>>> my_dict['b'] = b
>>> my_dict['c'] = c
>>>
>>> n='a1'
>>> print my_dict[n[0]][int(n[1])]
But before that it should be your responsibility to check if the entered list and indices exists.
Upvotes: 1
Reputation: 117550
I'd say the correct way would be to organize your lists into the dictionary and then use it like this:
>>> A = [0, 1, 2]
>>> B = [3, 4, 5]
>>> data = {'A':A, 'B':B}
>>> data['B'][1]
4
or, in your case:
>>> data[n[0].upper()][n[1]]
4
Upvotes: 2