理解程序

时间:2013-03-01 18:30:49

标签: python python-3.x sudoku

def cross(A, B):
    "Cross product of elements in A and elements in B."
    return [a+b for a in A for b in B]

digits   = '123456789'
rows     = 'ABCDEFGHI'
cols     = digits
squares  = cross(rows, cols)
unitlist = ([cross(rows, c) for c in cols] +
            [cross(r, cols) for r in rows] +
            [cross(rs, cs) for rs in ('ABC','DEF','GHI') for cs in ('123','456','789')])
units = dict((s, [u for u in unitlist if s in u]) 
             for s in squares)
peers = dict((s, set(sum(units[s],[]))-set([s]))
             for s in squares)

有人可以帮我理解(简单来说)最后两行的含义吗?

1 个答案:

答案 0 :(得分:0)

units = dict((s, [u for u in unitlist if s in u]) 
             for s in squares)

相同
units = dict()
for s in squares:
    units[s] = [u for u in unitlist if s in u]

或甚至类似于以下低效版本

units = dict()
for s in squares:
    units[s] = []
    for u in unitlist:
        if s in u:
            units[s].append(u)