Reputation: 25
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
Upvotes: 2
Views: 18699
Reputation: 2788
you can iterate thought the list :
>>> for i in range(len(list_two)):
... for j in range(len(list_one)):
... if list_two[i]==list_one[j]:
... list_3.append(j)
>>> list_3
[8, 5, 12, 12, 15]
but wim's answer is more elegant !
Upvotes: 1
Reputation: 1335
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]
Upvotes: 3
Reputation: 43169
Use .index()
on a list:
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"]
string = "hello"
positions = [list_one.index(c) for c in string]
print(positions)
# [8, 5, 12, 12, 15]
Upvotes: 0
Reputation: 1807
the x.index(i)
returns the position of the element i
of the list x
print("".join([str(list_one.index(i)) for i in list_two]))
85121215
Upvotes: 0
Reputation: 362567
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
.
Upvotes: 9