Python转换疯狂

Python转换疯狂,python,syntax,for-loop,list-comprehension,Python,Syntax,For Loop,List Comprehension,我有一个与python相关的代码理解问题: def convex_hull(pts): """Returns the points on the convex hull of pts in CCW order.""" for m in (2 ** (2 ** t) for t in xrange(len(pts))): hulls = [_graham_scan(pts[i:i + m]) for i in xrange(0, len(pts), m)] //mo

我有一个与python相关的代码理解问题:

def convex_hull(pts):
    """Returns the points on the convex hull of pts in CCW order."""
    for m in (2 ** (2 ** t) for t in xrange(len(pts))):
        hulls = [_graham_scan(pts[i:i + m]) for i in xrange(0, len(pts), m)]
//more code
我想不出这两个“for”应该如何工作

遗憾的是,命令引用并没有显示这样的用法示例,我也不知道它是否真的意味着一个for是另一个的左侧赋值

此外,底部的作业可能意味着什么?“for”语句是否返回值


感谢并对初学者提出的问题表示歉意。

要理解此代码,首先需要理解和。下面是一个简单列表理解的示例:

>>> [str(i) for i in range(5)]
['0', '1', '2', '3', '4']
如您所见,这一行相当于以下常规
for
循环:

lst = []
for i in range(5):
    lst.append(str(i))
基本上,它是创建列表的简写。生成器表达式与之类似,不同的是它们返回的生成器不是列表,而是生成与列表理解相同的值,而不实际创建完整列表。当您只是循环遍历这些值时,这会更有效

现在背景已经不存在了,下面是如何使用常规的
for
循环来扩展代码:

def convex_hull(pts):
    """Returns the points on the convex hull of pts in CCW order."""
    for t in xrange(len(pts)):
        m = 2 ** (2 ** t)
        hulls = []
        for i in xrange(0, len(pts), m):
            hulls.append(_graham_scan(pts[i:i + m]))
    # more code
至于你的评论,
pts[i:i+m]
从索引
i
到索引
i+m
,你基本上可以阅读这样的片段:

[first index to include : first index to exclude : step]

用一些例子做了很好的解释。

哈,太好了!这开始有意义了。最后一件事:你能告诉我pts[i:i+m]是什么意思吗?我猜这是一个子数组吗?@roamcel-请看我的编辑,这种语法称为切片,它的功能与您想象的完全相同:)此函数的第一行是一种非常糟糕的编码风格<代码>对于X范围内的t(len(pts)):m=2**2**t更快、更短,因此更易于阅读。