检查列表列表是否具有大小相等的列表 [英] Checking to see if a list of lists has equal sized lists

查看:64
本文介绍了检查列表列表是否具有大小相等的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要验证列表列表是否在python中具有相同大小的列表

I need to validate if my list of list has equally sized lists in python

myList1 = [ [1,1] , [1,1]] // This should pass. It has two lists.. both of length 2
myList2 = [ [1,1,1] , [1,1,1], [1,1,1]] // This should pass, It has three lists.. all of length 3
myList3 = [ [1,1] , [1,1], [1,1]] // This should pass, It has three lists.. all of length 2
myList4 = [ [1,1,] , [1,1,1], [1,1,1]] // This should FAIL. It has three list.. one of which is different that the other 

我可以编写循环以遍历列表并检查每个子列表的大小.有没有更Python的方法来达到目的.

I could write a loop to iterate over the list and check the size of each sub-list. Is there a more pythonic way to achieve the result.

推荐答案

all(len(i) == len(myList[0]) for i in myList)

为避免产生每个项目len(myList [0])的开销,您可以将其存储在变量中

To avoid incurring the overhead of len(myList[0]) for each item, you can store it in a variable

len_first = len(myList[0]) if myList else None
all(len(i) == len_first for i in myList)

如果您还希望看到为什么,它们并不完全相同

If you also want to be able to see why they aren't all equal

from itertools import groupby
groupby(sorted(myList, key=len), key=len)

将列表按长度分组,以便您可以轻松地看到奇数个

Will group the lists by the lengths so you can easily see the odd one out

这篇关于检查列表列表是否具有大小相等的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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