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

2024-06-11 05:13:27 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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)

Tags: inboard元素列表for字典数字dd
3条回答

这就是你可能正在寻找的

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}")

使用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])
}

相关问题 更多 >