python - Replacing elements in a list with the indices of a list containing all unique elements -
assume have list contains unique nodes a-d of graph:
list1 = [a, b, c, d] and list, contains edges of graph pairs of elements:
list2 = [[c, d], [b, a], [d, a], [c, b]] how can write fast , economic way replace elements of list2 indices of elements in list1, get:
list3 = [(2, 3), (1, 0), (3, 0), (2, 1)] my current way of doing is:
for in range(len(list2)): list3[i] = (list1.index(list2[i][0]), list1.index(list2[i][1])) however, takes long time large list, , trying find potentially faster way this.
you can create dict letters indices want
>>> indices = {key: index index, key in enumerate(list1)} >>> indices {'b': 1, 'd': 3, 'a': 0, 'c': 2} then use nested list comprehension
>>> [[indices[i] in sub] sub in list2] [[2, 3], [1, 0], [3, 0], [2, 1]] edit
list of tuple
>>> [tuple(indices[i] in sub) sub in list2] [(2, 3), (1, 0), (3, 0), (2, 1)]
Comments
Post a Comment