python中的列表列表?

Pra*_*are 1 python list-comprehension list

我需要一个很好的函数来在python中执行此操作.

def foo(n):
    # do somthing
    return list_of_lists

>> foo(6)
   [[1],
    [2,3],
    [4,5,6]]
>> foot(10)
    [[1],
    [2,3],
    [4,5,6]
    [7,8,9,10]]
Run Code Online (Sandbox Code Playgroud)

Ale*_*lli 9

def foo(n):
  lol = [ [] ]
  i = 1
  for x in range(n):
    if len(lol[-1]) >= i:
      i += 1
      lol.append([])
    lol[-1].append(x)
  return lol
Run Code Online (Sandbox Code Playgroud)


Geo*_*lly 8

def foo(n):
    i = 1
    while i <= n:
        last = int(i * 1.5 + 1)
        yield range(i, last)
        i = last

list(foo(3))
Run Code Online (Sandbox Code Playgroud)

当你使用数字时,你期望什么行为n不起作用,比如9?


dan*_*gph 5

改编自gs的答案,但没有神秘的"1.5".

def foo(n):
    i = c = 1
    while i <= n:
        yield range(i, i + c)
        i += c
        c += 1

list(foo(10))
Run Code Online (Sandbox Code Playgroud)