用等效于matlab find替换python中的循环 [英] Replace a loop in python with the equivalent of a matlab find

查看:503
本文介绍了用等效于matlab find替换python中的循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个元组的排序数组,该数组按第一个值排序.我想找到第一个索引,其中元组的第一个元素上的条件成立.即如何替换以下代码

Assume I have a sorted array of tuples which is sorted by the first value. I want to find the first index where a condition on the first element of the tuple holds. i.e. How do I replace the following code

test_array = [(1,2),(3,4),(5,6),(7,8),)(9,10)]
min_value = 5
index = 0
for c in test_array:
        if c[0] > min_value:
           break
        else:
            index = index + 1

与matlab等效吗?

With the equivalent of a matlab find ?

即在此循环结束时,我希望得到3,但我想使其更有效.我为此使用numpy很好.我尝试使用argmax,但无济于事.

i.e. At the end of this loop I expect to get 3 but I'd like to make this more efficient. I an fine with using numpy for this. I tried using argmax but to no avail.

谢谢

推荐答案

由于列表已排序,并且如果您知道第二个元素的最大可能值(或者如果只有一个具有相同第一个值的元素),您可以将bisect应用于元组列表(返回列表中已排序的插入位置)

Since the list is sorted and if you know the max possible value for the second element (or if there can only be 1 element with the same first value), you could apply bisect on the list of tuples (returns the sorted insertion position in the list)

import bisect
test_array = [(1,2),(3,4),(5,6),(7,8),(9,10)]
min_value = 5

print(bisect.bisect_left(test_array,(min_value,10000)))

硬编码为10000是不好的,因此,如果您只有整数,则可以这样做:

Hardcoding to 10000 is bad, so if you only have integers you can do that instead:

print(bisect.bisect_left(test_array,(min_value+1,)))

结果:3

如果您有浮点数(也适用于整数),则可以这样使用sys.float_info.epsilon:

if you had floats (also works with integers) you could use sys.float_info.epsilon like this:

print(bisect.bisect_left(test_array,(min_value*(1+sys.float_info.epsilon),)))

它具有O(log(n))的复杂性,因此在元素很多的情况下,它比简单的for循环要好得多.

It has O(log(n)) complexity so it's much better than a simple for loop when there are a lot of elements.

这篇关于用等效于matlab find替换python中的循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆