【发布时间】:2021-04-21 20:49:31
【问题描述】:
我想在 python 中对任何“pos”长度进行概括
for a in range(pos[0]):
for b in range(pos[1]):
for c in range(pos[2]):
for d in range(pos[3]):
for e in range(pos[4]):
for f in range(pos[5]):
neighbours.append([a, b, c, d, e, f])
我想在 6 个维度上收集我位置的所有邻居。邻居是所有坐标的x-1、x 和x+1 的所有组合。所以我必须收集 3^dim -1 个邻居。 pos 是一个 {dim} 长度列表,其中包含所有坐标的位置。 dx 是离散化长度。正如您所看到的,所有循环都是相同的,除了pos 中的索引增加,所以如果可能的话,我想概括一下。
for a in range(pos[0]- self.dx, pos[0]+2*self.dx, self.dx):
for b in range(pos[1]- self.dx, pos[1]+2*self.dx, self.dx):
for c in range(pos[2]- self.dx, pos[2]+2*self.dx, self.dx):
for d in range(pos[3]- self.dx, pos[3]+2*self.dx, self.dx):
for e in range(pos[4]- self.dx, pos[4]+2*self.dx, self.dx):
for f in range(pos[5]- self.dx, pos[5]+2*self.dx, self.dx):
neighbours.append([a, b, c, d, e, f])
【问题讨论】:
-
for item in pos: -
查找
intertools包,特别是应用于项目列表的product方法。语法类似于neighbours = list(product(pos*)) -
错字:
itertools
标签: python python-3.x for-loop