我需要验证我的列表列表是否在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
Run Code Online (Sandbox Code Playgroud)
我可以写一个循环迭代列表并检查每个子列表的大小.是否有更多的pythonic方式来实现结果.
Joh*_*ooy 16
all(len(i) == len(myList[0]) for i in myList)
Run Code Online (Sandbox Code Playgroud)
为避免每个项目产生len(myList [0])的开销,可以将其存储在变量中
len_first = len(myList[0]) if myList else None
all(len(i) == len_first for i in myList)
Run Code Online (Sandbox Code Playgroud)
如果你也想知道为什么他们并不都是平等的
from itertools import groupby
groupby(sorted(myList, key=len), key=len)
Run Code Online (Sandbox Code Playgroud)
将按长度对列表进行分组,以便您可以轻松查看奇数列表
你可以尝试:
test = lambda x: len(set(map(len, x))) == 1
test(myList1) # True
test(myList4) # False
Run Code Online (Sandbox Code Playgroud)
基本上,你得到每个列表的长度,并从这些长度创建一个集合,如果它包含一个元素,那么每个列表具有相同的长度