使用列表推导

时间:2017-03-02 10:36:31

标签: python list-comprehension

说一个列表a = [4, 8, 5, 7, 7, 7, 7, 3, 2, 2, 2, 5, 3, 3, 3, 3, 3]有没有办法用列表理解创建这个列表?

a = [4,8,5,(4乘7),3,(3乘2),5,(5乘3)]

我知道如何只使用一个重复值,而不是三个非重复值。

1 个答案:

答案 0 :(得分:7)

如果您尝试使用硬编码计数创建文字列表,则通过连接可以更轻松地实现这一目标:

a = [4, 8, 5] + 4 * [7] + [3] + 3 * [2] + [5] + 5 * [3]

如果必须使用列表推导,则必须为每个值包含一个乘数,然后使用双循环重复这些值:

# list of (count, value) pairs
inputs = [(1, 4), (1, 8), (1, 5), (4, 7), (1, 3), (3, 2), (1, 5), (5, 3)]
a = [i for count, i in inputs for _ in range(count)]

演示:

>>> [4, 8, 5] + 4 * [7] + [3] + 3 * [2] + [5] + 5 * [3]
[4, 8, 5, 7, 7, 7, 7, 3, 2, 2, 2, 5, 3, 3, 3, 3, 3]
>>> inputs = [(1, 4), (1, 8), (1, 5), (4, 7), (1, 3), (3, 2), (1, 5), (5, 3)]
>>> [i for count, i in inputs for _ in range(count)]
[4, 8, 5, 7, 7, 7, 7, 3, 2, 2, 2, 5, 3, 3, 3, 3, 3]