我需要验证我的列表列表在 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的方法来实现结果。
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)
将按长度对列表进行分组,以便您可以轻松地看到奇怪的列表
你可以尝试:
test = lambda x: len(set(map(len, x))) == 1
test(myList1) # True
test(myList4) # False
基本上,您可以获得每个列表的长度并根据这些长度创建一个集合,如果它包含单个元素,则每个列表具有相同的长度
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
如果您想在失败案例中获得更多数据,您可以这样做:
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
作为一名计算数学家,我建议使用
variance
长度。零方差意味着所有值都相等。
import statistics
def check_same_lengh(iterables):
variation = statistics.variance(len(iterable) for iterable in iterables)
if variation != 0:
raise ValueError('Their lengths are not the same.')
iterables = [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
check_same_lengh(iterables)