praa
praa

Reputation: 147

Given a 2D list of print range based on column

I currently have a 2D list. The list will always be 2 rows but it can be multiple columns

idx = [[0,4],[2, 6]] or idx = [[0,4,2,7],[2,6,5,10]]

and I need to generate a range based on the column, where the first row indicates the lower bound and the second row indicates the upper bound, inclusively.

For example on the first column idx[0] it should generate 0,1,2 and the second idx[1] should generate 4,5,6 and so on.

This is my code for a list idx = [1,2] but I don't know how to do it for 2d list.

    for i in range(len(idx)):
        for j in range(idx[i]):
            print(j)

Upvotes: 0

Views: 183

Answers (1)

Nguyen Thai Binh
Nguyen Thai Binh

Reputation: 346

Since you need a way to pair up the corresponding numbers in each row, it's a good idea to use zip here.

idx = [[0, 4, 2, 7], [2, 6, 5, 10]]
for lower, upper in zip(*idx):
    print(list(range(lower, upper + 1))) # upper limit inclusive
    # or create an output list and append to it

From Python help text,

The zip object yields n-length tuples, where n is the number of iterables passed as positional arguments to zip(). The i-th element in every tuple comes from the i-th iterable argument to zip(). This continues until the shortest argument is exhausted.

You can find more information about zip by typing help(zip) in any Python interpreter.

Upvotes: 1

Related Questions