python - Why nested list indexing gets swapped with list comprehensions? -
i expected following 2 code-segments equivalent.
return tuple(tuple( false if (i,j) in neighborhood else avail[i][j] in range(len(avail))) j in range(len(avail[i]))) (false, false, true, true, true) (false, false, true, true, true) (false, false, true, true, true) (false, false, true, true, true) (true, true, true, true, true) ls = [[val val in row] row in avail] in range(len(avail)): j in range(len(avail[i])): if (i,j) in neighborhood: ls[i][j] = false return ls [false, false, false, false, true] [false, false, false, false, true] [true, true, true, true, true] [true, true, true, true, true] [true, true, true, true, true]
the 1 for-loops "correct" (thats wanted). why did list comprehension-version swap indexes?
you have loops inverted in first version. creating inner tuples looping on range(len(avail))
, outer tuples loop on range(len(avail[i]))
.
your code equivalent (with lists instead of tuples) of instead:
outer = [] j in range(len(avail[i])): inner = [] in range(len(avail)): inner.append(false if (i,j) in neighborhood else avail[i][j]) outer.append(inner)
and relied on i
still being assigned global. can see when indent expression based on parenthesis:
return tuple( tuple( false if (i,j) in neighborhood else avail[i][j] in range(len(avail)) ) j in range(len(avail[i])) )
reverse loops (indented differently communicate grouping better):
return tuple( tuple(false if (i,j) in neighborhood else avail[i][j] j in range(len(avail[i]))) in range(len(avail)))
the above equivalent of:
outer = [] in range(len(avail)): inner = [] j in range(len(avail[i])): inner.append(false if (i,j) in neighborhood else avail[i][j]) outer.append(inner)
you can simplify code using enumerate()
:
return tuple( tuple(false if (i,j) in neighborhood else v j, v in enumerate(row)) i, row in enumerate(avail))
Comments
Post a Comment