首页 > 解决方案 > 在某些数组位置查找重复的数字

问题描述

在此处输入图像描述

我正在尝试根据从另一个数组中获取的位置在多维数组中查找重复值。上图正是我想要做的。

对于"positions array"中的每个位置(或需要的行),检查 "numbers array" 中是否存在与第一个匹配的任何重复数字

上图的示例应返回(打印)如下内容:

并且应该忽略其他所有内容。

尝试了一千个不同的循环,但我失败了。

编辑:一个不工作的例子,下面

print(finalValues)
for symbol in finalValues[0]:
    count = 0
    for line in lines:
        for i in range(0, len(line)):
            if finalValues[i][line[i]] == symbol:
                count += 1
        if count > 2:
            print("Repeated number: {}, count: {}, line: {}".format(symbol, count, line))

编辑:数字示例(取自上图)

- We are looping through positions, and in the first loop we have positions: 1,1,1
- We should check numbers[0][1], numbers[1][1], numbers[2][1]
- In the next loop we have positions: 0,0,0
- We should check numbers[0][0], numbers[1][0], numbers[2][0]
- In the next loop we have positions: 2,2,2
- We should check numbers[0][2], numbers[1][2], numbers[2][2]
- In the next loop we have positions: 0,1,2
- We should check numbers[0][0], numbers[1][1], numbers[2][2]

标签: pythonarrayspython-3.xloopsfor-loop

解决方案


我们可以使用内置zip函数来并行循环一行中的项目numbers和对应lines的行。下面的代码打印出每一行选择的值,lines以确保我们得到了我们真正想要的项目。

一旦我们有了选择,我们就head, *tail = selected可以将第一个项目head和其余项目放入一个名为 的列表中tail,这样我们就可以计算连续重复的次数。

代码

lines = [
    [1,1,1],
    [0,0,0],
    [2,2,2],
    [0,1,2],
    [2,1,0],
]

def test(numbers):
    for row in lines:
        selected = [num[val] for num, val in zip(numbers, row)]
        print(row, '->', selected)
        head, *tail = selected
        count = 1
        for val in tail:
            if val == head:
                count += 1
            else:
                break
        if count > 2:
            print("Repeated number: {}, count: {}, line: {}".format(head, count, row))        

# Some test data
print("Testing...")
numbers = [[3, 4, 1], [3, 3, 5], [3, 7, 3]]
print('numbers', numbers)
test(numbers)    

print("Some more tests...")

# Some more test data
nums = [
    [[2, 2, 2], [4, 2, 2], [4, 2, 7]], 
    [[1, 3, 3], [5, 4, 3], [3, 4, 2]],
    [[7, 1, 6], [2, 1, 1], [1, 1, 5]], 
]

for numbers in nums:
    print('\nnumbers', numbers)
    test(numbers)    

输出

Testing...
numbers [[3, 4, 1], [3, 3, 5], [3, 7, 3]]
[1, 1, 1] -> [4, 3, 7]
[0, 0, 0] -> [3, 3, 3]
Repeated number: 3, count: 3, line: [0, 0, 0]
[2, 2, 2] -> [1, 5, 3]
[0, 1, 2] -> [3, 3, 3]
Repeated number: 3, count: 3, line: [0, 1, 2]
[2, 1, 0] -> [1, 3, 3]
Some more tests...

numbers [[2, 2, 2], [4, 2, 2], [4, 2, 7]]
[1, 1, 1] -> [2, 2, 2]
Repeated number: 2, count: 3, line: [1, 1, 1]
[0, 0, 0] -> [2, 4, 4]
[2, 2, 2] -> [2, 2, 7]
[0, 1, 2] -> [2, 2, 7]
[2, 1, 0] -> [2, 2, 4]

numbers [[1, 3, 3], [5, 4, 3], [3, 4, 2]]
[1, 1, 1] -> [3, 4, 4]
[0, 0, 0] -> [1, 5, 3]
[2, 2, 2] -> [3, 3, 2]
[0, 1, 2] -> [1, 4, 2]
[2, 1, 0] -> [3, 4, 3]

numbers [[7, 1, 6], [2, 1, 1], [1, 1, 5]]
[1, 1, 1] -> [1, 1, 1]
Repeated number: 1, count: 3, line: [1, 1, 1]
[0, 0, 0] -> [7, 2, 1]
[2, 2, 2] -> [6, 1, 5]
[0, 1, 2] -> [7, 1, 5]
[2, 1, 0] -> [6, 1, 1]

推荐阅读