简体   繁体   中英

Replacing elements in a list with the indices of a list containing all unique elements

Assume I have a list which contains the unique nodes A - D of a graph:

List1 = [A, B, C, D]

And another list, which contains the edges of a graph with pairs of the elements:

List2 = [[C, D], [B, A], [D, A], [C, B]]

How can I write a fast and economic way to replace all elements of List2 with the indices of the elements in List1 , so that I get:

List3 = [(2, 3), (1, 0), (3, 0), (2, 1)]

My current way of doing this is:

for i in range(len(List2)):
    List3[i] = (List1.index(List2[i][0]), List1.index(List2[i][1]))

However, this takes a really long time for a large list, and I was trying to find a potentially faster way to do this.

You can create a dict from your letters to the indices you want

>>> indices = {key: index for index, key in enumerate(List1)}
>>> indices
{'B': 1, 'D': 3, 'A': 0, 'C': 2}

Then use a nested list comprehension

>>> [[indices[i] for i in sub] for sub in List2]
[[2, 3], [1, 0], [3, 0], [2, 1]]

Edit
To get a list of tuple

>>> [tuple(indices[i] for i in sub) for sub in List2]
[(2, 3), (1, 0), (3, 0), (2, 1)]

You can use list comprehension and index method of list to achieve what you want.

List1 = ['A', 'B', 'C', 'D']

List2 = [['C', 'D'], ['B', 'A'], ['D', 'A'], ['C', 'B']]

print [ (List1.index(item[0]),List1.index(item[1])) for item in List2]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM