2016-04-05 7 views
4

私はいくつかのチュートリアルの演習で、Pythonの理解について学習しています。私は、(0,0,0)の些細な例を除いて、0に合計された与えられた集合の数のすべての組み合わせの3組を返す理解を構築するよう求めてきました。フィルタリングpython list comprehensions

私はこの思い付いた:

def tupleNonTrivialSumation(s): 
    '''return a 3-tuple of x,y,z : x+y+z=0 & the list does not contain (0,0,0)''' 
    return tuple([(x,y,z) for x in s for y in s for z in s if x+y+z==0 if abs(x)+abs(y)+abs(z)!=0])` 

がこれを書くために、より簡潔な方法はありますか? x、y、zの合計が0になっているかどうかを調べる良い方法があるはずです。順序が重要な場合は

答えて

4

あなたはitertools.permutation()使用することができます。

from itertools import permutation 
[sub for sub in permutation(s, 3) if sum(sub) == 0 and sub != (0, 0, 0)] 

をそれ以外の場合は「パイソンの禅」に続きitertools.combinations()

+0

'[... if sum(sub)== 0 and sub!=(0、0、0)]'? 「(0,0,0)の簡単な例」を除外する必要はありませんか? – Alexander

+0

@Alexanderはい、確かです。 – Kasramvd

0

を使用し、私はちょうどフィルタ条件に簡単な変更を加えるでしょう:

[(x, y, z) for x in s for y in s for z in s if x + y + z == 0 and (x, y, z) != (0, 0, 0)] 
0

まあ、すべてのの組み合わせが必要ですではないpあなたがsumする必要があるので、 ermutations。

import itertools 
cs = itertools.combinations(sequence, 3) 
result = [c for c in cs if sum(c) == 0 and any(c)]