简体   繁体   中英

Converting a single dimensional array into two dimension

Problem is below:

A two dimensional array is presented as one dimensional array of integers. The first integer of the array denote the length of the each row of the 2d array. The remaining integers are the each element of the array, first of row 1 and then row 2 and so on

For example:

array = [5,11,12,13,14,15,16,17,18,19,20]

11,12,13,14,15
16,17,18,19,20

if I query it like arr[1,2] = 12

I am trying to convert c++ code into python as below but facing problem, I am quite new to python

def get_ar(arr, query):
    t = arr[0]
    k = arr[1]
    for i in range t:
        // go to new line

But this is not logical way of solving it

Here is a simple way of solving it.

for i in range(1,len(array),array[0]) creates a range with i equal to 1 (skips 0 because we don't want the first number in array ), then adds the value of array[0] each time.

array[i:i+array[0]] selects the range of values from i until i+array[0] , which will give you array[0] elements in total.

array = [5,11,12,13,14,15,16,17,18,19,20]

array2d = [array[i:i+array[0]] for i in range(1,len(array),array[0])]
output = []
for i in range(len(array)//array[0]):
  output.append(array[i*array[0]+1:(i+1)*array[0]+1])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM