简体   繁体   English

python 中最有效的计算方式在对列表中查找对

[英]Most efficient computational way in python find pairs in a list of pairs

I need to find if pair exists in a list of pairs.我需要查找对是否存在于对列表中。 I can use a standard for loop with if statement, but is there a more computationally efficient way?我可以使用带有 if 语句的标准 for 循环,但是有没有一种计算效率更高的方法?

Current my data looks like:目前我的数据如下:

alist = [(12970, 12980), (12970, 13000), (12970, 13012)]
pair = [12970, 13000]

for a in list:
   if a == pair:
       print("do something")

I have tried using the following but it did not return a match:我尝试使用以下内容,但没有返回匹配项:

if pair in alist:
    print("do something")

Any other suggestions?还有其他建议吗?

pair is a list of two integers. pair是两个整数的列表

alist has elements that are tuples . alist具有元组元素。

Since these are not even of the same base type, they will not compare as equal.由于它们甚至不是相同的基本类型,因此它们不会相等。

Try尝试

alist = [(12970, 12980), (12970, 13000), (12970, 13012)]
pair = (12970, 13000)    # tuple, not list
if pair in list:
    ...

If your problem requirements don't let you change the original values, then cast the type in-line:如果您的问题要求不允许您更改原始值,则将类型转换为内联:

if tuple(pair) in list:

If the alist is sorted you can use bisect which should have complexity O(log n).如果alist已排序,则可以使用复杂度 O(log n) 的bisect

Copying from module docs:从模块文档复制:

import bisect

def index(a, x):
    'Locate the leftmost value exactly equal to x'
    i = bisect.bisect_left(a, x)
    if i != len(a) and a[i] == x:
        return i
    raise ValueError

index(alist, (12970, 13000))

If there is no element found you will get ValueError如果没有找到元素,你会得到ValueError

You could also go with converting alist to set.您还可以 go 将alist转换为设置。 Then the average complexity should be O(1) on lookup那么查找时的平均复杂度应该是 O(1)

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

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