簡體   English   中英

過濾python列表理解

[英]filtering python list comprehensions

我正在學習一些有關python理解的教程練習。 我遇到了一個要求建立一個理解,它返回給定集合中所有數字組合的3元組,總和為零 - 不包括(0,0,0)的簡單例子。

我想出了這個:

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總和是否為零。

如果訂單很重要,您可以使用itertools.permutation()

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

否則使用itertools.combinations()

遵循“Python的禪”,我只想對過濾條件進行簡單的更改:

[(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)]

好吧,你需要所有的組合而不是排列,因為你需要sum它們。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM