Pythonic方法创建递减序列列表

时间:2018-03-02 22:23:17

标签: python

而不是:

l_1 = range(0, 10056, 24)
l_2 = range(0, 10032, 24)
l_3 = range(0, 10008, 24)
...
l_419 = range(0, 0, 24)
l_together = list(l_1, l_2, ..., l_419)

如何以更Pythonic的方式创建具有递减序列的列表列表?

2 个答案:

答案 0 :(得分:4)

您可以使用简单的列表理解来完成此操作:

[range(0, i, 24) for i in reversed(range(0, 10056 + 1, 24))]

这相当于简单的for循环:

result = []
for i in reversed(range(0, 10056 + 1, 24)):
    result.append(range(0, i, 24))

其中一个是完美的和pythonic。

或者,用简化的例子来证明:

>>> n = 100
>>> step = 10
>>> result = [range(0, i, step) for i in reversed(range(0, n+1, step))]
>>> from pprint import pprint
>>> pprint(result)
[range(0, 100, 10),
 range(0, 90, 10),
 range(0, 80, 10),
 range(0, 70, 10),
 range(0, 60, 10),
 range(0, 50, 10),
 range(0, 40, 10),
 range(0, 30, 10),
 range(0, 20, 10),
 range(0, 10, 10),
 range(0, 0, 10)]

答案 1 :(得分:1)

bigL = []
diminish = 24
i = 10056
while i >= 0: ## Just abstracting the code to easily modify it ... this will run while i is positive
    bigL.append(range(0, i, diminish)) ## Supply i and diminish and then append the list to bigL 
    i -= diminish ## Reduce i by diminish (by 24 in this case)