2012-05-30 28 views
4

我需要验证,如果我的清单列表中有在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方式来实现结果。

回答

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

威尔组列出了长度,所以你可以很容易地看到鹤立鸡群

+0

我在这里看到的问题是(如果编译器没有优化它),你正在计算索引0的列表长度n次加上1次计算每个其他列表,这使得2 * n长度计算。 –

+2

@SanSS,长度不是_calculated_,它是一个属性。如果你确实需要微小的速度提升,你可以将它存储在一个变量中。当列表为空时,您必须特殊处理 –

+0

如果将'all'的参数嵌套到列表中,让这个工作起作用有点麻烦吗? 'all([len(i)== len(myList [0])for myList])' – FriskyGrub

4

你可以尝试:

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

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

基本上,你会得到每一个列表的长度,并从这些长度进行设置,如果它包含一个单一的元素,则每个列表具有相同的长度

+5

在序列中早期存在不同长度的情况下,这不是非常有效。你仍然会不必要地检查其余部分 –

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 
1
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 
+0

我不明白为什么这应该downvote?如果列表很大,可能使用'* args'不是一个好主意,因为您将制作副本)。当我看到我的答案是一个处理'len(args)== 0'的情况的技巧 –

相关问题