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

后端 未结 3 2001
谎友^
谎友^ 2021-01-18 21:53

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 n

相关标签:
3条回答
  • 2021-01-18 22:28

    You can do this,

    maxLen = max(map(len, arr))
    [row.extend(['null']*(maxLen - len(row))) for row in arr]
    
    0 讨论(0)
  • 2021-01-18 22:41

    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.

    0 讨论(0)
  • 2021-01-18 22:46

    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.

    0 讨论(0)
提交回复
热议问题