简体   繁体   中英

Taking n elements at a time from 1d list and add them to 2d list

I have a list making up data, and I'd like to take 4 elements at a time from this list and put them in a 2d list where each 4-element increment is a new row of said list.

My first attempts involve input to 1d list: list.append(input("Enter data type 1:")) list.append(input("Enter data type 2:")) etc. and then I've tried to loop the list and to "switch" rows once the index reaches 4.

for x in range(n * 4):
    for idx, y in enumerate(list):
        if idx % 4 == 0:
            x = x + 1
            list[y] = result[x][y]

where I've initialised result according to the following: and

ran = int(len(list)/4)

result=[[0 for x in range(ran)] for j in range(n)]

I've also attempted to ascribe a temporary empty list that will append to an initialised 2D list. `

row.append(list)
     
result=[[x for x in row] for j in range(n + 1)]
#result[n]=row
print(result)
n = n + 1
row.clear()
list.clear()

so that each new loop starts with an empty row, takes input from user and copies it. I'm at a loss for how to make result save the first entry and not be redefined at second,third,fourth entries.

I think this post is probably what you need. With np.reshape() you can just have your list filled with all the values you need and do the reshaping after in a single step.

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