2012-05-30 29 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'的情況的技巧 –

相關問題