分页: 1 / 1

Python 的性能问题

发表于 : 2013-04-23 0:46
Hello World!
最近在琢磨A*算法。

程序中经常要执行
[python]for i in self.close:
if node.x == i.x and node.y == i.y:
return True
return False[/python]和[python]for i, n in enumerate(self.open):
if node.x == n.x and node.y == n.y:
return i
return -1[/python]这两段。请问,能不能使用 “in” 来代替程序中的循环呢?谢谢。

Re: Python 的性能问题

发表于 : 2013-04-26 12:16
ciahly
in是什么意思?我只知道用列表推导式。

第一个:

代码: 全选

 if [True for i in self.close if node.x == i.x and node.y == i.y] :
...
如果一个True也没有,就是空列表,对if来说就是False.

第二个:

代码: 全选

[i for i,n in enumerate(self.open) if node.x == i.x and node.y == i.y]
据说列表推导式会比循环快。

Re: Python 的性能问题

发表于 : 2013-06-16 21:34
lilydjwg
ciahly 写了:in是什么意思?我只知道用列表推导式。

第一个:

代码: 全选

 if [True for i in self.close if node.x == i.x and node.y == i.y] :
...
如果一个True也没有,就是空列表,对if来说就是False.

第二个:

代码: 全选

[i for i,n in enumerate(self.open) if node.x == i.x and node.y == i.y]
据说列表推导式会比循环快。
但是你这样就没有短路的效果了。

Re: Python 的性能问题

发表于 : 2013-07-25 22:13
Kabie

代码: 全选

any(node.x, node.y == i.x, i.y for i in self.close)

代码: 全选

next(itertools.dropwhile(lambda i,n:(node.x, node.y != n.x, n.y), enumerate(self.open)))