9

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

4 回答 4

19
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)

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

于 2012-05-30T22:25:06.793 回答
7

你可以试试:

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

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

基本上,您获取每个列表的长度并从这些长度中创建一个集合,如果它包含单个元素,则每个列表具有相同的长度

于 2012-05-30T22:23:39.493 回答
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
于 2012-05-30T22:34:24.377 回答
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
于 2012-05-30T22:28:29.973 回答