我正在构建一个数独游戏,我发现一个site可以为我提供100万个预生成的游戏。 我下载了文件(CSV),并希望为前端使用做准备。 每个游戏都有81个数字,例如
346179258187523964529648371965832417472916835813754629798261543631485792254397186
974183652651274389283596714129835476746912538835647921568329147317468295492751863
563472198219386754847195623472638519951247386638519472795864231324951867186723945
我想创建所有拼图的JS或JSON文件,以便将其导入我的代码中。 这是每个游戏(线)的理想结果。
[
[5, 3, 4, 6, 7, 8, 9, 1, 2],
[6, 7, 2, 1, 9, 5, 3, 4, 8],
[1, 9, 8, 3, 4, 2, 5, 6, 7],
[8, 5, 9, 7, 6, 1, 4, 2, 3],
[4, 2, 6, 8, 5, 3, 7, 9, 1],
[7, 1, 3, 9, 2, 4, 8, 5, 6],
[9, 6, 1, 5, 3, 7, 2, 8, 4],
[2, 8, 7, 4, 1, 9, 6, 3, 5],
[3, 4, 5, 2, 8, 6, 1, 7, 9]
]
这是我在python中设法完成的事情
import csv
import json
holder = []
rows = []
def divide_chunks(l, n):
# looping till length l
for i in range(0, len(l), n):
yield l[i:i + n]
with open('sudoku.csv', newline='') as csvfile:
counter = 0
n = 9
s=','
reader = csv.DictReader(csvfile)
for row in reader:
if counter > 10:
break
print(row['solutions'])
print(len(row['solutions']))
test = [int(str(row['solutions']))]
#chunk = divide_chunks(test, n)
# for val in enumerate(chunk):
# val = [val]
# # for index,item in enumerate(val):
# # item[index] = item+s
# # print(val)
holder.append(test)
counter +=1
print(holder)
with open('puzzles.json', 'w') as outputfile:
json.dump(holder,outputfile)
这是到目前为止我在puzzles.json中的输出
[
[864371259325849761971265843436192587198657432257483916689734125713528694542916378],
[346179258187523964529648371965832417472916835813754629798261543631485792254397186],
[695127384138459672724836915851264739273981546946573821317692458489715263562348197],
[497258316186439725253716498629381547375964182841572639962145873718623954534897261],
[465912378189473562327568149738645291954821637216397854573284916642159783891736425],
[194685237382974516657213489823491675541768923769352841215839764436527198978146352],
[289765431317924856645138729763891542521473968894652173432519687956387214178246395],
[894231657762495183351876942583624719219387564647159328128763495976542831435918276],
[563472198219386754847195623472638519951247386638519472795864231324951867186723945],
[163725948584693271729184365946358127371462589852917634498231756637549812215876493],
[974183652651274389283596714129835476746912538835647921568329147317468295492751863]
]
有什么建议吗? 谢谢
答案 0 :(得分:2)
您可以通过列表理解将字符串分成数字
sudoku = 346179258187523964529648371965832417472916835813754629798261543631485792254397186
sudoku_list = [number for number in str(sudoku)]
然后您通过使用另一个列表理解将其分成9个长度的块
sudoku_final = [sudoku_list[9*i:9*i+9] for i in range(9)]
如果您希望输出为整数而不是字符串,请在列表理解中使用int(number) for number in str(sudoku)
答案 1 :(得分:1)
使用Python,您可以将所有数字转换为字符串,然后将其转换回列表,如下所示:
tuple(map(int, str(x))) # x is the 81 digit number.
这样,您可以将81位数字的列表分成9x9的网格,如下所示(迭代9的倍数并取下9个数字):
[x[i: i + 9] for i in range(0, 81, 9)]