Mainland
Mainland

Reputation: 4574

Python Reshape a list with odd number of elements

I have a list with an odd number of elements. I want to convert it into a specific size.

My code:

alist = ['a','b','c']
cols= 2
rows = int(len(alist)/cols)+1 # 2
anarray = np.array(alist.extend([np.nan]*((rows*cols)-len(months_list)))).reshape(rows,cols)

Present output:

ValueError: cannot reshape array of size 1 into shape (2,2)

Expected output:

anarray  = [['a','b'],['c',nan]]

Upvotes: 1

Views: 925

Answers (3)

Quang Hoang
Quang Hoang

Reputation: 150775

You can try:

out = np.full((rows,cols), np.nan, dtype='object')

out.ravel()[:len(alist)] = alist

Output:

array([['a', 'b'],
       ['c', nan]], dtype=object)

As a side note, this might be better for you:

rows = int(np.ceil(len(alist)/cols))

Upvotes: 5

balderman
balderman

Reputation: 23815

Try (without any external library)

import math

alist = ['a', 'b', 'c']
cols = 2
new_list = []
steps = math.ceil(len(alist) / cols)
start = 0
for x in range(0, steps):
    new_list.append(alist[x * cols: (x + 1) * cols])
new_list[-1].extend([None for t in range(cols - len(new_list[-1]))])
print(new_list)

output

[['a', 'b'], ['c', None]]

Upvotes: 1

Shivam Jha
Shivam Jha

Reputation: 4522

You can use list comprehension to achieve the result:

li = ['a','b','c']
l = len(li)

new_list = [li[x:x+2] for  x in range(l // 2)]
if l % 2 != 0:
    new_list.append([li[-1], None])
print(new_list) # [['a', 'b'], ['c', None]]

Upvotes: 1

Related Questions