使用数字创建列表每次Python都会变得更好

Bel*_*ish 8 python loops list while-loop

如何创建一个能够创建列表的函数,每次将其包含的数量增加到指定值?

例如,如果max为4,则列表将包含

1, 2, 2, 3, 3, 3, 4, 4, 4, 4
Run Code Online (Sandbox Code Playgroud)

很难解释我在寻找什么,但从这个例子我认为你会理解!

谢谢

mgi*_*son 17

我用的是itertools.chain:

itertools.chain(*([i] * i for i in range(1, 5)))
Run Code Online (Sandbox Code Playgroud)

或者itertools.chain.from_iterable稍微懒散一点:

itertools.chain.from_iterable([i] * i for i in range(1, 5))
Run Code Online (Sandbox Code Playgroud)

对于最终的懒惰,配对itertools.repeat- (使用xrange你使用python2.x):

import itertools as it
it.chain.from_iterable(it.repeat(i, i) for i in range(1, 5))
Run Code Online (Sandbox Code Playgroud)

作为一个功能:

def lazy_funny_iter(n):
    return it.chain.from_iterable(it.repeat(i, i) for i in range(1, n+1))

def lazy_funny_list(n):
    return list(lazy_funny_iter(n))
Run Code Online (Sandbox Code Playgroud)


Inb*_*ose 16

A Nested loop. This would be a very basic way to do it. There are much better ways, this should give you the general idea.

>>> def listmaker(num):
    l = []
    for i in xrange(1, num+1):
        for j in xrange(i):
            l.append(i)
    return l

>>> print listmaker(4)
[1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
Run Code Online (Sandbox Code Playgroud)

Here is doing it with list comprehension:

>>> def listmaker2(num):
    return [y for z in [[x]*(x) for x in xrange(1, num+1)] for y in z]

>>> print listmaker2(4)
[1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
Run Code Online (Sandbox Code Playgroud)

Using extend as suggested.

>>> def listmaker3(num):
    l = []
    for i in xrange(1, num+1):
        l.extend([i]*(i))
    return l

>>> print listmaker3(4)
[1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
Run Code Online (Sandbox Code Playgroud)


E.Z*_*.Z. 9

您可以使用递归函数:

def my_func(x):
    if x <= 0:
        return []
    else:
        return my_func(x-1) + [x] * x

>>> my_func(4)
[1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
Run Code Online (Sandbox Code Playgroud)


Lev*_*sky 7

In [1]: def funny_list(n):
   ...:     return sum(([i]*i for i in range(1, n+1)), [])
   ...: 

In [2]: funny_list(4)
Out[2]: [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
Run Code Online (Sandbox Code Playgroud)

然而,这不能变成真正的发电机,不像itertools.chain,这是规范的方式.

  • 用这种方式使用`sum`时要注意的一件事是它会显示二次行为,所以如果`n`是(比方说)100,它将比`itertools.chain'长几百倍.当然,这通常无关紧要. (4认同)
  • 有趣地使用`sum` (2认同)