python中的列表?

2024-09-29 21:20:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要一个好的函数在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]]

Tags: of函数returnfoodefdolistslist
3条回答
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

改编自gs的答案,但没有神秘的“1.5”。在

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

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

list(foo(3))

当你对n使用一个不起作用的数字(如9)时,你期望有什么行为?在

相关问题 更多 >

    热门问题