首页 > 解决方案 > Is it possible to shorten several layers of 'for in' with actions at each layer?

问题描述

I am solving a Sudoku kata on Codewars and here is my code:

def valid_solution(S):
    s=[];L=[];l=[];S1=S[:3];S2=S[3:6];S3=S[6:]
    def verif(S):
        for i in S:
            if len(set(i))!=9 or 0 in set(i): return False
    for z in range(0,9):
        for i in range(len(S)): s.append(S[i][z])
        L.append(s);s=[]
    def loop(h):
        x=3;y=0;s=[];l=[]
        for z in range(len(h)):
            for i in range(3): s.append(h[i][y:x])
            y+=3;x+=3;l.append(s);s=[]
        return l
    l=loop(S1)+loop(S2)+loop(S3)
    for i in range(len(l)):
        for z in range(len(l[i])): l[i][z]=''.join(list(map(str,l[i][z])))
        l[i]=''.join(l[i])
    return False if verif(L)==False or verif(S)==False or verif(l)==False else True

I was wondering if there were a way to make it shorter, not by using matrix etc., but by making 'for in' loops shorter.

Exemple:

for z in range(0,9):
        for i in range(len(S)): s.append(S[i][z])
        L.append(s);s=[]

-->

[(L.append(s),s=[]) [s.append(S[i][z] for z in range(0,9)] for i in range(len(S))]

Thanks in advance.

标签: pythonfor-loopaesthetics

解决方案


推荐阅读