CDo*_*Doc 3 python arrays loops for-loop python-3.x
我试图根据从另一个数组中获取的位置在多维数组中查找重复值。上图正是我想要做的。
对于“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))
Run Code Online (Sandbox Code Playgroud)
编辑:数字示例(取自上图)
- 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]
Run Code Online (Sandbox Code Playgroud)
我们可以使用内置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)
Run Code Online (Sandbox Code Playgroud)
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]
Run Code Online (Sandbox Code Playgroud)