我預計以下2個代碼段基本上是等效的。爲什麼嵌套列表索引與列表解析交換?
return tuple(tuple(False if (i,j) in neighborhood else avail[i][j]
for i in range(len(avail)))
for 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 for val in row] for row in avail]
for i in range(len(avail)):
for 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]
帶for-loops的那個是「正確的」(那就是我想要的)。爲什麼列表理解版本交換索引?
請忽略列表元組差異 – user1358