简体   繁体   中英

How to make array of arrays in python?

I have an array like ['a','b','c','d','e','f'] . How can i convert it to an array of arrays such that [['a','b'],['c','d'],['e','f']]

I have tried appending it normally but it give some random result

inputArr = input.split(',')
i=0
Yy = []
while i < len(inputArr):
    temp = [inputArr[i], inputArr[i+1]]
    Yy.append(temp)
    i += 2

Output: [ 'a', 'b,c', 'd,e', 'f' ]

I tried your code and got no error. However, if you did, you can try this way:

new_list = [lst[i:i+2] for i in range(0, len(lst), 2)]

This outputs: [['a', 'b'], ['c', 'd'], ['e', 'f']] , using list comprehension, which I suppose is what you want.

If you wanted an output of [['a', 'b', 'c'], ['d', 'e', 'f']] , then change the i:i+2 to i:i+3 and change (0, len(lst), 2) at the end to (0, len(lst), 3) .

use can use numpy:

import numpy as np

a = ['a','b','c','d','e','f']
n = np.array(a)
print(n.reshape(3,2))

You can use range wich takes (start, stop, step)

lst = ['a','b','c','d','e','f']
new_lst = []
for i in range(0,len(lst), 2):
    new_lst.append(lst[i:i+2])
print(new_lst)

notice that we step twice and slice the list with 2 futher index positions. output: [['a', 'b'], ['c', 'd'], ['e', 'f']]

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