检查列表列表是否具有大小相等的列表
问题描述:
我需要验证列表列表是否在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