Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make all lists in a list of lists the same length by adding to them

I have a nested list which contains lists filled with strings. What I am trying to do is make each list in this nest the same length as the longest available list in that nest. This sounds easy, but my attempts have failed (I am completely new to programming) and I cannot find an answered question which is relative enough to solve my problem.

First, I determine how long the longest list is:

maxSS7 = max(len(i) for i in ssValues7))

Then, I use a for loop to extend each list by a certain amount of 'null' if it is not the same length as the longest list:

for row in ssValues7:
    if row < len(maxSS7):
        row.extend(['null' * (len(maxSS7) - len(row))])

I am extending the row by 'null' * the difference between the longest list and current list. No errors occur, but unfortunately it appears to do nothing to my nested list.

Could someone please enlighten me as to my error? Any help would be greatly appreciated.

like image 827
foushad Avatar asked Sep 23 '12 08:09

foushad


3 Answers

The expression 'null' * (len(maxSS7) - len(row)) creates one potentially very long string.

Use

row.extend('null' for _ in xrange(maxSS7 - len(row)))

instead. The generator expression lets you avoid creating an extra list object just to extend row.

>>> ['null' * 2]
['nullnull']
>>> ['null' for _ in xrange(2)]
['null', 'null']

But the .extend call itself is never reached, as you if statement is testing the wrong thing; change it to:

 if len(row) < maxSS7:

maxSS7 is aready a number (the length of the longest list); asking that number for it's length is not what you were looking for.

like image 140
Martijn Pieters Avatar answered Sep 18 '22 02:09

Martijn Pieters


The problem is with the line:

if row < len(maxSS7):

You're comparing the list row with the integer len(maxSS7). It will evaluate to False each time. Change it to:

maxLen = max(map(len, myList))
for row in myList:
    if len(row) < maxLen:
        row.extend(...)

Martijn Peters pointed another problem with your code in his answer.

like image 28
Joel Cornett Avatar answered Sep 22 '22 02:09

Joel Cornett


You can do this,

maxLen = max(map(len, arr))
[row.extend(['null']*(maxLen - len(row))) for row in arr]
like image 28
Avishka Dambawinna Avatar answered Sep 19 '22 02:09

Avishka Dambawinna