Checking to see if a list of lists has equal sized lists

前端 未结 4 886
梦谈多话
梦谈多话 2021-01-12 12:32

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         


        
相关标签:
4条回答
  • 2021-01-12 13:01
    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

    0 讨论(0)
  • 2021-01-12 13:06
    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
    
    0 讨论(0)
  • 2021-01-12 13:18

    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
    
    0 讨论(0)
  • 2021-01-12 13:22

    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

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