如何在列表理解中嵌套for循环?

时间:2019-08-14 05:42:07

标签: python-3.x list list-comprehension nested-lists

我已经为make list编写了以下代码。

# in_put = 3,4
# 3 item in each sublist
# total 4 sublist
# out_put = [ [1,2,3] , [4,5,6] , [7,8,9] , [10,11,12] ]

def my_lc(m,n):
    out_put = []
    temp = []
    element =1
    for i in range(1,n+1):
        for j in range(1,m+1):
            temp.append(element)
            element += 1
        out_put.append(temp.copy())
        temp.clear()
    return out_put

print(my_lc(3,4))

如何使用列表理解来编写my_lc()函数?

1 个答案:

答案 0 :(得分:1)

这应该有效:

def my_lc(m, n):
    return [list(range(m * i + 1, (i + 1) * m + 1)) for i in range(n)]

print(my_lc(3, 4))
# [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]

或使用itertools.count

from itertools import count

def my_lc(m, n):
    c = count(1)
    return [list(next(c) for _ in range(m)) for _ in range(n)]