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
m
all(len(i) == len(myList[0]) for i in myList)
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
def equalSizes(*args):
"""
# This should pass. It has two lists.. both of length 2
>>> equalSizes([1,1] , [1,1])
True
# This should pass, It has three lists.. all of length 3
>>> equalSizes([1,1,1] , [1,1,1], [1,1,1])
True
# This should pass, It has three lists.. all of length 2
>>> equalSizes([1,1] , [1,1], [1,1])
True
# This should FAIL. It has three list.. one of which is different that the other
>>> equalSizes([1,1,] , [1,1,1], [1,1,1])
False
"""
len0 = len(args[0])
return all(len(x) == len0 for x in args[1:])
To test it save it to a file so.py
and run it like this:
$ python -m doctest so.py -v
Trying:
equalSizes([1,1] , [1,1])
Expecting:
True
ok
Trying:
equalSizes([1,1,1] , [1,1,1], [1,1,1])
Expecting:
True
ok
Trying:
equalSizes([1,1] , [1,1], [1,1])
Expecting:
True
ok
Trying:
equalSizes([1,1,] , [1,1,1], [1,1,1])
Expecting:
False
ok
If you want a little more data in failure cases, you could do:
myList1 = [ [1,1] , [1,1]]
lens = set(itertools.imap(len, myList1))
return len(lens) == 1
# if you have lists of varying length, at least you can get stats about what the different lengths are
You could try:
test = lambda x: len(set(map(len, x))) == 1
test(myList1) # True
test(myList4) # False
Basically, you get the length of each list and make a set from those lengths, if it contains a single element then each list has the same length