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 に答える