简体   繁体   中英

how to make these even elements append to this two dimensional array 5x5

How to make these even elements append to this two dimensional 5 elements per each array and numbers gradually evenly increasing each array not repeating themselves each array.

multiarray = [[], [], [], [], []]
for i in range(2,150,2):
    for indexRow in range(len(multiarray)):
        multiarray[indexRow].append(i)
    i = i + 1
    if len(multiarray[0]) >= 5:
        break
print(multiarray)

The following simplification will work:

multiarray = [[], [], [], [], []]

i = iter(range(2, 150, 2))

for array in multiarray:
    for _ in range(5):
        array.append(next(i))

The whole thing can of course be brought to one line:

multiarray = [list(range(2*5*i+2, 2*5*(i+1)+2, 2)) for i in range(5)]

Another hint: use itertools.count to produce an infinite amount of regular numbers lazily:

from itertools import count

# i = iter(range(2, 150, 2))
i = count(2, step=2)

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