2

I have 2 lists, one has unique values and the other has repeating values from the first list, I want to modify the second list to contain index positions of the first list as the new values.

list_2 should be [0, 0, 2, 1, 0]

This is the solution I have but I was wondering if it could be done in 1 line, in list_2 without creating a new list.

list_1 = ['a', 'b', 'c']
list_2 = ['a','a','c','b','a']


# new should be [0, 0, 2, 1, 0]
new = []
for i,j in enumerate (list_1):
    for i in list_1:
        if i in list_2:
            new = [list_1.index(p) for p in list_2]

3 Answers3

1

One way is to create a dictionary out of values and indices in list_1 then use this dictionary as look up for the values in list_2 and call dict.get for each values in list_2, you can do this in a List-Comprehension:

>>> list_1_dict=dict(zip(list_1, range(len(list_1))))
>>> [list_1_dict.get(v) for v in list_2]

[0, 0, 2, 1, 0]

The advantage of creating look up dictionary is you won't have to go back to the list again and again to find the index of particular value which is often less efficient vs getting a value in dict has O(1) complexity. Also, dict.get returns None if the key doesn't exist.

ThePyGuy
  • 17,779
  • 5
  • 18
  • 45
0

You could do it like this except if a value in list_2 doesn't exist in list_1 you'll get ValueError:

list_1 = ['a', 'b', 'c']
list_2 = ['a','a','c','b','a']

new = [list_1.index(c) for c in list_2]

print(new)

Output:

[0, 0, 2, 1, 0]
DarkKnight
  • 19,739
  • 3
  • 6
  • 22
0

how about this list comprehension method?

list_1 = ['a', 'b', 'c']
list_2 = ['a','a','c','b','a']
new = [list_1.index(p) for p in list_2]
print(new)

Output:

[0, 0, 2, 1, 0]
blackraven
  • 5,284
  • 7
  • 19
  • 45