Python list comprehension trick

时间:2015-07-28 17:07:51

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

It's probably a silly question, but...

list = []
for i in range(1, 5):
    for j in range(i):
        list.append(i)
print(list)

list2 = [[i]*i for i in range(1, 5)]
print(list2)

With following code my output is like

[1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
[[1], [2, 2], [3, 3, 3], [4, 4, 4, 4]]

I understand why the second one looks like this, but are there any tricks to get the first list with comprehension?
P.S.
Python 3

5 个答案:

答案 0 :(得分:8)

Is this what you want?

>>> list2 = [i for i in range(1, 5) for j in range(i)]
>>> list2
[1, 2, 2, 3, 3, 3, 4, 4, 4, 4]

Trick is to put similar for loops in same order inside the list comprehension (and since you do not need list of lists, do not create those).

答案 1 :(得分:3)

[i for i in range(5) for j in range(i)] should do the trick. You can use multiple fors in a list comprehension.

答案 2 :(得分:2)

While I prefer the double for, you could also use reduce using list2:

list1 = reduce(lambda x, y: x + y, [[i] * i for i in range(1, 5)])
print list1
# [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]

答案 3 :(得分:2)

在我的代码段中,我可以添加sum以获得相同的输出:

>>> sum([[i]*i for i in range(1, 5)], [])
[1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
>>>

或使用reduce:

>>> reduce(lambda x,y: x+y, [[i]*i for i in range(1, 5)])
[1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
>>>

如果你不喜欢这个解决方案,请告诉我。我会将其删除。

答案 4 :(得分:0)

使用迭代工具,

from itertools import chain, repeat

list2 = list(chain.from_iterable(repeat(i, i) for i in range(1, 5)))

print(list2)
[1, 2, 2, 3, 3, 3, 4, 4, 4, 4]

[Program finished]