3

タプルのリストから分割表を作成しようとしています。リストは次のようになります。

lst = [('a', 'bag'), ('a', 'bag'), ('a', 'bag'), ('a', 'cat'), ('a', 'pen'), ('that', 'house'), ('my', 'car'), ('that', 'bag'), ('this', 'bag')]

たとえば、タプルが与えられた場合、次の('a', 'bag')4 つのことを解決する必要があります。

a = lst.count(('a', 'bag'))です3

bはすべてのタプルの数でありtuple[0] == 'a' and tuple[1] != 'bag'、それは 2:('a', 'cat'), ('a', 'pen')です。

やってみると

lst.count(('a', not 'bag'))0となるはずですが、を取得します2-----1

cはすべてのタプルの数ですtuple[0] != 'a' and tuple[1] == 'bag'。この場合、('that', 'bag'), ('this', 'bag'). でもやってみると

lst.count((not 'a', 'bag'))0となるはずですが、を取得します2-----2

dはすべてのタプルの数で、tuple[0] !== 'a' and tuple[1] != 'bagから簡単に取得できますlen(lst) - a

私の質問: or で論理ゲートを組み合わせる方法はありnotますlst.count((x, not y))lst.count((not x, y))? そうでない場合は、複雑さが非常に高くつくため、ループなしでうまくいく方法bを教えてください。c2(N*N)

あなたの親切な助けは本当に感謝しています!

4

3 に答える 3

0

このように、1回のパスで4つの組み合わせすべてをカウントする関数を定義できます

>>> def my_count(iterable,a,b):
        both    = 0
        a_not_b = 0
        not_a_b = 0
        neither = 0 
        for x,y in iterable:
            if x == a and y == b:
                both += 1
            if x == a and y!= b:
                a_not_b += 1
            if x != a and y == b:
                not_a_b += 1
            if x!= a and y!= b:
                neither += 1
        return both, a_not_b, not_a_b, neither

>>> lst = [('a', 'bag'), ('a', 'bag'), ('a', 'bag'), ('a', 'cat'), ('a', 'pen'), ('that', 'house'), ('my', 'car'), ('that', 'bag'), ('this', 'bag')]
>>> my_count(lst,"a","bag")
(3, 2, 2, 2)
>>>         

より冗長にするために、このような nametuple を追加できます

>>> from collections import namedtuple
>>> CountTuple = namedtuple("CountTuple","both a_not_b not_a_b neither")
>>> def my_count(iterable,a,b):
        #same as before 
        ...
        return CountTuple(both,a_not_b,not_a_b,neither)

>>> result = my_count(lst,"a","bag")
>>> result
CountTuple(both=3, a_not_b=2, not_a_b=2, neither=2)
>>> result.both
3
>>> result.a_not_b
2
>>> result.not_a_b
2
>>> result.neither
2
>>>     
于 2016-03-18T21:37:16.553 に答える