Is there a way to increment a variable within a single-lined for loop?

Viewed 72

Given the following definitions

layerData = [3, 3, 2, 1, 1]

bias = [0.47, -0.45, 0.31, -0.09, 0.21 ,-0.18, 0.14, -0.45, -0.39, -0.14]

Starting at the head of the bias list, for each element N in layerData I would like to take the next N elements from bias and append that list to the result

This is what it should output:

[[0.47, -0.45, 0.31], [-0.09, 0.21, -0.18], [0.14, -0.45], [-0.39], [-0.14]]
2 Answers

You can use an iterator - call next on it each time you want a value.

>>> bias = [0.47, -0.45, 0.31, -0.09, 0.21 ,-0.18, 0.14, -0.45, -0.39, -0.14]
>>> layerData = [3, 3, 2, 1, 1]
>>> it = iter(bias)
>>> [[next(it) for _ in range(n)] for n in layerData]
[[0.47, -0.45, 0.31], [-0.09, 0.21, -0.18], [0.14, -0.45], [-0.39], [-0.14]]

Use itertools.accumulate for a running total of layerData. This allows to extract the sub-list directly as slices instead of individual items:

>>> from itertools import accumulate
>>>
>>> layerData = [3, 3, 2, 1, 1]
>>> bias = [0.47, -0.45, 0.31, -0.09, 0.21 ,-0.18, 0.14, -0.45, -0.39, -0.14]
>>>
>>> [bias[i-n:i] for i, n in zip(accumulate(layerData), layerData)]
[[0.47, -0.45, 0.31], [-0.09, 0.21, -0.18], [0.14, -0.45], [-0.39], [-0.14]]
Related