Python:查找两个数组之间* first *匹配项的索引 [英] Python: Find indices of the *first* match between two arrays

查看:102
本文介绍了Python:查找两个数组之间* first *匹配项的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试比较从零索引开始的两个数组,以查找arrayA中的第一次 any 元素第一次匹配arrayB中的 any 元素-以及每个数组中的对应位置数组。



问题是,我编写的代码与匹配元素的 last 实例匹配-我不确定为什么。 / p>

这是我的代码:

 对于数组A中的a:
代表arrayB中的b:$ a $ b如果a == b:
indexA = arrayA.index(a)
indexB = arrayB.index(b)

arrayA = ['j','e','b','a'] arrayB = ['k','e','b','a'] 。代码返回 indexA = 3 indexB = 3 (与'a'匹配),但是我很喜欢返回 indexA = 1 indexB = 1 (与'e'匹配)。



任何建议,我们将不胜感激!

解决方案

问题是一旦发现,您就会继续循环播放第一场比赛。找到匹配项时,您需要中断。另外,您实际上不需要嵌套循环。

 对于arrayA中的a:
如果arrayB中的a:
indexA = arrayA.index(a)
indexB = arrayB.index(a)
休息


I'm trying to compare two arrays starting at the zeroth index to find the first time any element in arrayA matches any element in arrayB - and corresponding positions within each array.

The issue is, the code I've written is matching the last instance of matched elements - I'm not quite sure why.

Here's my code:

for a in arrayA:
     for b in arrayB:
          if a == b:
              indexA = arrayA.index(a)
              indexB = arrayB.index(b)

Say arrayA = ['j', 'e', 'b', 'a'] and arrayB = ['k', 'e', 'b', 'a']. The code returns indexA = 3 and indexB = 3 (matching on 'a'), whereas I'd like it to return indexA = 1 and indexB = 1 (matching on 'e').

Any suggestions greatly appreciated!

解决方案

The problem is that you keep looping once you've found the first match. When you find a match you need to break out of the loop. Also, you actually don't need the nested loop.

for a in arrayA:
    if a in arrayB:
        indexA = arrayA.index(a)
        indexB = arrayB.index(a)
        break

这篇关于Python:查找两个数组之间* first *匹配项的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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