检查列表列表是否具有相同大小的列表

时间:2012-05-30 22:18:34

标签: list python

我需要验证我的列表列表是否在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 

我可以写一个循环迭代列表并检查每个子列表的大小。是否有更多的pythonic方式来实现结果。

4 个答案:

答案 0 :(得分:15)

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

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

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

如果您还希望能够看到为什么它们并非完全相同

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

将按长度对列表进行分组,以便您可以轻松查看奇数列表

答案 1 :(得分:6)

你可以尝试:

test = lambda x: len(set(map(len, x))) == 1

test(myList1) # True
test(myList4) # False

基本上,你获得每个列表的长度并根据这些长度设置一个集合,如果它包含单个元素,则每个列表具有相同的长度

答案 2 :(得分:3)

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

要测试它,请将其保存到文件so.py并按以下方式运行:

$ 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

答案 3 :(得分:0)

如果您想在失败案例中获得更多数据,可以这样做:

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