【发布时间】:2015-09-13 19:52:43
【问题描述】:
所以,我有四个列表。两个保存 x 坐标(foodX 和 newPosXArray),另外两个保存 y 坐标(foodX 和 newPosYArray)。 food 和 newPos 数组都具有不同的维度,因为我有多个“食物来源”和多个搜索食物的对象。
我想写一个 if 语句,当物体到达食物的一定距离内时,它会做一些事情。
我对any()的尝试
if any(np.sqrt((newPosXArray[u]-foodX[t])**2 + (newPosYArray[u]-foodY[t])**2) <= 0.2 for t in zip(food[0], food[1]) for u in zip(newPosXArray, newPosYArray)):
#dosomething
我收到一个错误 TypeError: list indices must be integers, not tuple
编辑: 也许我误解了 zip()。我假设它浓缩了这个
if any(np.sqrt((newPosXArray[u]-foodX[t])**2 + (newPosYArray[u]-foodY[t])**2) <= 0.2 for t in foodX for t in foodY for u in newPosXArray for u in newPosYArray):
我所使用的典型值
foodX = [5,5,-5,-5]
foodY = [5,-5,5,-5]
In [65]: newPosXArray
Out[65]:
[-0.012880860643600167,
-0.566815786730638,
0.7905336304903405,
0.09006991095474826,
0.26518652615441063,
0.3161232055076695,
0.681255361368023,
-0.6849985596071202,
0.7140832628874829,
0.4958515031060564]
In [66]: newPosYArray
Out[66]:
[-0.41112817779983235,
-0.08554837651693648,
0.8743935617169996,
-0.9384733737088207,
0.02423386678116546,
-0.3735855691077572,
-0.5251118585489394,
0.3950871276165102,
0.9892320167752822,
-0.7342372054958279]
当然,这些值都不会在 if 语句中返回 true,因为它们都不在任何食物坐标的 0.2 半径范围内
【问题讨论】:
-
不确定您处理的项目数量,但如果数量很少,则可以通过创建保存坐标的对象,然后创建
calcDistance方法来提高代码清晰度。class Point(object): def __init__(self, x, y): self.x=x, self.y=ydef calcDistance(self, otherPoint): return math.sqrt((self.x - otherPoint.x)**2 + (self.y - otherPoint.y)**2)。然后你的循环变成:if any(f.calcDistance(y) for f in food for y in newPos):
标签: python arrays for-loop numpy any