简体   繁体   English

用包含所有唯一元素的列表索引替换列表中的元素

[英]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: 假设我有一个列表,其中包含图的唯一节点A - D

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: 如何编写一种快速经济的方法,用List1元素的索引替换List2所有元素,从而得到:

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 您可以从字母到所需索引创建dict

>>> 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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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