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

I have a nested list that contains lists filled with strings. What I'm trying to do is make each list in this slot the same length as the longest available list in this slot. It sounds simple, but my attempts failed (I am completely new to programming), and I cannot find an answer that is resolved enough to solve my problem.

First, I determine how long the list is long:

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

Then I use the for loop to expand each list by a specific number 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 expanding the string to 'null' * the difference between the longest list and the current list. No errors occur, but unfortunately it does nothing for my nested list.

Can someone please enlighten me regarding my mistake? Any help would be greatly appreciated.

+2
source share
2 answers

The problem is the line:

 if row < len(maxSS7): 

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

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

Martijn Peters pointed out another issue with your code in his answer .

+3
source

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

Using

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

instead of this. A generator expression avoids creating an additional list object for row expansion only.

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

But the .extend call .extend never reached, because if you say you are testing the wrong thing; change it to:

  if len(row) < maxSS7: 

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

+6
source

Source: https://habr.com/ru/post/1275188/


All Articles