Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

finding an element from one list in another list in python

Is there a way to have two lists named list1 and list2 and be able to look up the position of one entry in another. i.e.

list_one = ["0", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]

list_two = ["h","e","l","l","o"]

my aim is to allow the user to enter a word which the program will then convert in a set of numbers corresponding to the letters entries in list_one

so if the user did input hello the computer would return 85121215 (being the position of the entries)

is there a possible way to do this

like image 289
D. Forrester Avatar asked Jan 29 '26 02:01

D. Forrester


2 Answers

Looking up the position of an item in a list is not a very efficient operation. A dict is a better data structure for this kind of task.

>>> d = {k:v for v,k in enumerate(list_one)}
>>> print(*(d[k] for k in list_two))
8 5 12 12 15

If your list_one is always just the alphabet, in alphabetical order, it's probably better and simpler to get something working by using the builtin function ord.

like image 79
wim Avatar answered Jan 31 '26 15:01

wim


Adding to @wim's answer, could be done with a simple comprehension.

>>> [list_one.index(x) for x in list_two]
[8, 5, 12, 12, 15]
like image 31
Simeon Aleksov Avatar answered Jan 31 '26 16:01

Simeon Aleksov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!