LotOfQuestion
LotOfQuestion

Reputation: 65

How to split the list of number into sub list which depend on range

I just curious is there a way to split the list of number using it own range? Example:

original_list = [[0,3],[5,7]]

to

splited_list = [[0,1],[1,2],[2,3],[5,6],[6,7]]

Upvotes: 1

Views: 68

Answers (3)

Ajax1234
Ajax1234

Reputation: 71451

You can also use a list comprehension with zip:

l = [[0,3],[5,7]]
new_l = [[a, b] for c, d in l for a, b in zip(range(c, d+1), range(c, d+1)[1:])]

Output:

[[0, 1], [1, 2], [2, 3], [5, 6], [6, 7]]

Upvotes: 0

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

Simple and short approach (with range):

orig_list = [[0,3],[5,7]]
res = [[i, i+1] for a, b in orig_list for i in range(a, b)]
print(res)

The output:

[[0, 1], [1, 2], [2, 3], [5, 6], [6, 7]]

Upvotes: 2

Adi219
Adi219

Reputation: 4814

Try this:

original_list = [[0,3],[5,7]]
splitted_list = []

for rangeDef in original_list: ## for each range definition
    for i in range(rangeDef[0], rangeDef[1]): ## for each pair of numbers within that range
        splittedList.append([i, i + 1])

Upvotes: 2

Related Questions