将子列表中的每三个元素附加到字典

Append every three elements in sublist to dictionary

假设我有一个包含列表的列表。

board = [[5, 3, 0, 0, 7, 0, 1, 0, 0],
[6, 0, 0, 1, 9, 5, 0, 0, 0],
[0, 9, 8, 0, 0, 0, 0, 6, 0],
[8, 0, 0, 0, 6, 0, 0, 0, 3],
[4, 0, 0, 8, 0, 3, 0, 0, 1],
[7, 0, 0, 0, 2, 0, 0, 0, 6],
[0, 6, 0, 0, 0, 0, 2, 8, 0],
[0, 0, 0, 4, 1, 9, 0, 0, 5],
[0, 0, 0, 0, 8, 0, 0, 7, 9]]

我想将每个子列表中的每三个数字附加到字典中的一个键。 例如

dd = {1:[5, 3, 0,6, 0, 0,0, 9, 8]}

那我去找下一个3x3的部分。

dd = {2:[0,7,0,1,9,5,0,0,0]}

总共我应该有 9 个键,每个键都有 9 个元素的列表。

这显然行不通 XD:

board = [[5, 3, 0, 0, 7, 0, 1, 0, 0],
[6, 0, 0, 1, 9, 5, 0, 0, 0],
[0, 9, 8, 0, 0, 0, 0, 6, 0],
[8, 0, 0, 0, 6, 0, 0, 0, 3],
[4, 0, 0, 8, 0, 3, 0, 0, 1],
[7, 0, 0, 0, 2, 0, 0, 0, 6],
[0, 6, 0, 0, 0, 0, 2, 8, 0],
[0, 0, 0, 4, 1, 9, 0, 0, 5],
[0, 0, 0, 0, 8, 0, 0, 7, 9]]
xBx = {}
count1 = 1
count2 = 3
count3 = 0
for row in board:
   if count1 == 4:
       count = 1
   xBx[count1] = row[count3:count2]
   count1 += 1
   count2 += 3
   count3 += 3
   
print(xBx)

使用numpy,多维数组切片更简单

import numpy as np

board = np.array(board)
result = {}
for i in range(len(board) // size):
    for j in range(len(board) // size):
        values = board[j * size:(j + 1) * size, i * size:(i + 1) * size]
        result[i * size + j + 1] = values.flatten()

并且result给出

{
   1: array([5, 3, 0, 6, 0, 0, 0, 9, 8]), 
   2: array([8, 0, 0, 4, 0, 0, 7, 0, 0]), 
   3: array([0, 6, 0, 0, 0, 0, 0, 0, 0]), 
   4: array([0, 7, 0, 1, 9, 5, 0, 0, 0]), 
   5: array([0, 6, 0, 8, 0, 3, 0, 2, 0]), 
   6: array([0, 0, 0, 4, 1, 9, 0, 8, 0]), 
   7: array([1, 0, 0, 0, 0, 0, 0, 6, 0]), 
   8: array([0, 0, 3, 0, 0, 1, 0, 0, 6]), 
   9: array([2, 8, 0, 0, 0, 5, 0, 7, 9])
}

这可能是您正在寻找的

size = 3
l = len(board)

dict = {}
dictIndex = 1

for x in range(0, l, size):
    for y in range(0, l, size):
        a = []
        for i in range(x, x + size):
            for j in range(y, y + size):
                a.append(board[i][j])
        dict[dictIndex] = a
        dictIndex += 1

print(dict)

更短的变体

size, l, dict, dictIndex  = 3, len(board), {}, 1
for x in range(0, l, size):
    for y in range(0, l, size):
        dict[dictIndex], dictIndex = [board[i][j] for i in range(x, x + size) for j in range(y, y + size)], dictIndex + 1
print(dict)

这应该有效:

board = [[5, 3, 0, 0, 7, 0, 1, 0, 0],
[6, 0, 0, 1, 9, 5, 0, 0, 0],
[0, 9, 8, 0, 0, 0, 0, 6, 0],
[8, 0, 0, 0, 6, 0, 0, 0, 3],
[4, 0, 0, 8, 0, 3, 0, 0, 1],
[7, 0, 0, 0, 2, 0, 0, 0, 6],
[0, 6, 0, 0, 0, 0, 2, 8, 0],
[0, 0, 0, 4, 1, 9, 0, 0, 5],
[0, 0, 0, 0, 8, 0, 0, 7, 9]]

d = {}

for i in range(len(board[0]) // 3):
    for l in board:
        if i + 1 in d.keys():
            d[i + 1].append(l[0 + i*3])
            d[i + 1].append(l[1 + i*3])
            d[i + 1].append(l[2 + i*3])

        else:
            d[i + 1] = []
            d[i + 1].append(l[0 + i*3])
            d[i + 1].append(l[1 + i*3])
            d[i + 1].append(l[2 + i*3])

for key, value in d.items():
    print(f"{key}     {value}")