如何通过添加列表来使列表列表中的所有列表具有相同的长度 [英] How to make all lists in a list of lists the same length by adding to them

查看:34
本文介绍了如何通过添加列表来使列表列表中的所有列表具有相同的长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个嵌套列表,其中包含用字符串填充的列表.我想要做的是使这个嵌套中的每个列表的长度与该嵌套中最长的可用列表的长度相同.这听起来很简单,但我的尝试失败了(我对编程完全陌生)并且我找不到足以解决我的问题的已回答问题.

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))

然后,如果每个列表的长度与最长列表的长度不同,我将使用 for 循环将每个列表扩展一定数量的空":

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.

推荐答案

问题出在线路上:

if row < len(maxSS7):

您正在将 list rowinteger len(maxSS7) 进行比较.每次都会评估为 False.改为:

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 在他的回答中指出了您的代码的另一个问题.

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

这篇关于如何通过添加列表来使列表列表中的所有列表具有相同的长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆