首页 > 解决方案 > Python:长形式的数组 For 循环

问题描述

bracketized for在 Python 中,通过循环构建数组的简写形式是:

def get_row(runner):
    row = some_complicated_function()
    return row

my_array = [get_row(runner) for runner in range(10000)]

如果我想避免for循环的压缩形式,这会是什么样子?

标签: python

解决方案


以下代码片段(您提供的是列表理解)

my_array = [get_row(runner) for runner in range(10000)]

这是一个等效unrolled版本

my_array = []
for runner in range(10000):
    row_runner = get_row(runner)
    my_array.append(row_runner)
    # alternatively
    # my_array.append(get_row(runner))

推荐阅读