M.M
M.M

Reputation: 1373

Equating the lengths of the arrays in an array of arrays

Given an array of arrays with different lengths. Is there a cleaner (shorter) way to equate the lengths of the arrays by filling the shorter ones with zeros other than the following code:

a = [[1.0, 2.0, 3.0, 4.0],[2.0, 3.0, 1.0],[5.0, 5.0, 5.0, 5.0],[1.0, 1.0]]


max =0
for x in a:
    if len(x) > max:
        max = len(x)

print max
new = []
for x in a:
    if len(x)<max:
        x.extend([0.0]* (max-len(x)) )
    new.append(x)

print new

Upvotes: 2

Views: 58

Answers (2)

Eugene Yarmash
Eugene Yarmash

Reputation: 150031

You can find the length of the largest list within a using either:

len(max(a, key=len))

or

max(map(len, a))

and also use a list comprehension to construct a new list:

>>> a = [[1.0, 2.0, 3.0, 4.0], [2.0, 3.0, 1.0], [5.0, 5.0, 5.0, 5.0], [1.0, 1.0]]
>>> m = len(max(a, key=len))
>>> new = [x + [0]*(m - len(x)) for x in a]
>>> new
[[1.0, 2.0, 3.0, 4.0], [2.0, 3.0, 1.0, 0], [5.0, 5.0, 5.0, 5.0], [1.0, 1.0, 0, 0]]

Upvotes: 5

Juraj Bezručka
Juraj Bezručka

Reputation: 502

In: b = [i+[0.]*(max(map(len,a))-len(i)) for i in a]

In: b
Out: 
[[1.0, 2.0, 3.0, 4.0],
 [2.0, 3.0, 1.0, 0.0],
 [5.0, 5.0, 5.0, 5.0],
 [1.0, 1.0, 0.0, 0.0]]

Upvotes: 1

Related Questions