How to create a list contains alternating interval list of numbers?

Question:

I have 2 lists of numbers:

A = [1, 2, 3, 4,5, 6, 7, 8, 9, 10]

B = [101, 102, 103, 104, 105, 106, 107, 108, 109, 200] 

Then I would like to make a combination for each X and Y from each element of A and B with alternating interval as follows. The total elements of X and Y is always odd (3,5,…) until the last odd number before n. In the case of n = 10, then it is up to 9.

X = [A_1, B_2, A_3, ...,A_idx_odd], len(X) = odd
Y = [B_1, A_2, B_3, ...,B_idx_odd], len(Y) = odd

Then, for each combination of X and Y will be stored in the storage_X and storage_Y.

storage_X = [ [len(X) =3], [len(X) = 5], ..., [len(X) = 9]]

storage_Y = [ [len(Y) =3], [len(Y) = 5], ..., [len(Y) = 9]]

For example:


X = [1, 102, 3]               len(X) = 3
X = [1, 102, 3, 104, 105]     len(X) = 5

storage_X = [[1, 102, 3], [1, 102, 3, 104, 105], ....]   

Y = [101, 2, 103]             len(Y) = 3
Y = [101, 2, 103, 4, 105]     len(Y) = 5

storage_Y = [ [101, 2, 103], [101, 2, 103, 4, 105] , ....]

How can I do in python?
Thank you in advance.

Asked By: Nicholas Nicholas

||

Answers:

With pure python:

X_storage = [[[A, B][j%2][j] for j in range(i)] for i in range(3, len(A), 3)]
# [[1, 102, 3],
#  [1, 102, 3, 104, 5, 106],
#  [1, 102, 3, 104, 5, 106, 7, 108, 9]]

Y_storage = [[[B, A][j%2][j] for j in range(i)] for i in range(3, len(A), 3)]
# [[101, 2, 103],
#  [101, 2, 103, 4, 105, 6],
#  [101, 2, 103, 4, 105, 6, 107, 8, 109]]

Using :

A = [1, 2, 3, 4,5, 6, 7, 8, 9, 10]
B = [101, 102, 103, 104, 105, 106, 107, 108, 109, 200] 

m = np.arange(len(A))%2
X = np.where(m, B, A).tolist()
Y = np.where(m, A, B).tolist()

X_storage = [X[:i] for i in range(3, len(A), 3)]
# [[1, 102, 3], [1, 102, 3, 104, 5, 106], [1, 102, 3, 104, 5, 106, 7, 108, 9]]

Y_storage = [Y[:i] for i in range(3, len(A), 3)]
# [[101, 2, 103], [101, 2, 103, 4, 105, 6], [101, 2, 103, 4, 105, 6, 107, 8, 109]]
Answered By: mozway
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.