简体   繁体   中英

Modification of alternate index values in a 2D array - Python

I have a list -> m = [13, 8, 2, 9, 8, 8, 8, 8] . I am trying to calculate result = m%4 and place it in a 2D array at alternating positions (described by -1).

[[-1. 3. -1. 1.]
 [3. -1. 2. -1.]
 [-1. 1. -1. 0.]
 [3. -1. 1. -1.]]

I tried calculating the parity of the indexes (-1 occupies all indexes of odd parity) and placing the result there using a for loop but it just ends up replacing all the -1 with the result after each loop.

I want it to calculate the result for the first list item and then add it to the first '-1' position and then do the the same for the next result but this time adding it to the next '-1' and so on.

Any and all insights are appreciated, Thanks

Say your 2D list is

a = [[-1,0],[0,-1]]

A way to select all the -1 and replace the items would be:

m_index = 0
for i in range(len(a)):
    for j in range(len(a[-1])):
        if (i+j)%2 == 0:
            a[i][j] = m[m_index]%4
            m_index += 1

I believe this is not the most pythonic way to do the task, but it's the best that popped into my mind. Remember to be sure that len(m) matches with the number of -1s.

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