简体   繁体   English

python 元组列表中的元素索引

[英]Indices of elements in a python list of tuples

Problem问题

Given 2 lists A and B, I want to get the indices of all elements in List A which are present in List B. Each element is a tuple.给定 2 个列表 A 和 B,我想获取列表 B 中存在的列表 A 中所有元素的索引。每个元素都是一个元组。

I am using lists of size 40,000 elements or so.我正在使用大小为 40,000 个元素左右的列表。

Sample case样品案例

Input:输入:

A = [(1,2),(3,4),(5,6),(7,8)]

B = [(1,2),(3,4),(5,6)]

Expected output:预期 output:

[0,1,2]

Attempted solutions尝试的解决方案

I tried two solutions:我尝试了两种解决方案:

1) using map function 1) 使用 map function

m = map(a.index,b)
list(m)

2) using list comprehension 2) 使用列表理解

m = [a.index(item) for item in b if item in a]

These methods seem to be taking too much time.这些方法似乎花费了太多时间。 Is there any other way to accomplish this?有没有其他方法可以做到这一点?

Below would be your best bet.以下将是您最好的选择。 I am using a set (ie, set(B) ) as searching for the specific tuple can be done in O(1) Time Complexity.我正在使用一个集合(即set(B) ),因为可以在 O(1) 时间复杂度中完成对特定元组的搜索。

m = [index for index, tuple in enumerate(A) if tuple in set(B)]

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

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