找到两个列表相同的基于1的位置 [英] Find the 1 based position to which two lists are the same

查看:79
本文介绍了找到两个列表相同的基于1的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

挑战是编写一个函数来比较两个很小的整数列表(每个整数列表最多少于10个元素). 一个列表可能是这样的:

The challange is to write a function to compare two rather small lists of integers (mostly less than 10 elements each). One list could be something like:

self = [0, 0, 1, 2]

要与之进行比较的列表可能看起来像以下示例之一:

The lists which it is to be compared with could look like one of the following examples:

other1 = []
other2 = [0, 0, 1]
other3 = [0, 0, 1, 2, 0]
other4 = [0, 1, 1, 2]
other5 = something

如您所见,重复元素非常普遍,元素的顺序很重要.

As you can see, duplicate elements are quite common and the order of elements is important.

预期结果应该是一个整数,表示从头算起的self和other相同的时间.因此,取决于其他因素,结果将是:

The expected result should be an integer, representing how long self and other are the same, counted from the beginning. So depending on other, the result would be:

result1 = 0
result2 = 3
result3 = 4
result4 = 1
result5 = 0

该代码应该是最有效的,因为每次用户交互都要使用约100次.

The code should be most efficient, since it is to be used some 100 times for every user interaction.

我编写了以下代码,它可以按需工作,但似乎有点慢:

I coded the following, it works as desired, but seems to be kind of slow:

def match(self, other):
    if self == other:
        return len(self)
    element = -1
    for element in range(min(len(self),  len(other))):
        if self[element] != other[element]:
            element -= 1
            break
    return element +1

第一个if语句已经增强了速度,但是解决方案仍然很慢,并且对名为element的变量和两个return语句的所有更正也显得有些笨拙.

The first if statement is already an enhancement to speed things up, but the solution still seems slow and also looks a bit clumsy with all its corrections to the variable named element and the two return statements.

有人能说出比匹配"或比较"更好的功能吗?

Has anybody a name for such a function which is better than 'match' or 'compare'?

推荐答案

In a related question, I posted the following potential solutions:

def while_equal(seq, other):
    for this, that in zip(seq, other):
        if this != that:
            return
        yield this

def match(seq, other):
    return sum(1 for _ in while_equal(seq, other))

def match_loop(seq, other):
    count = 0
    for this, that in zip(seq, other):
        if this != that:
            return count
        count += 1
    return count

这些版本都比其他给定的解决方案快(第二个是最快的),而且我认为它更具可读性.

These versions are both faster than the other given solutions (the second being the fastest), and, I would argue, more readable.

这篇关于找到两个列表相同的基于1的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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