2012-09-12 26 views
0

可能重複:
python equivalent of filter() getting two output lists (i.e. partition of a list)的Python模擬對Ruby可枚舉.partition方法

是否有任何內置函數或Python標準庫,也許一些模塊,從模擬Enumerable.partition行爲Ruby並遍歷一個對象只需要一次,以獲得兩個基於謂詞函數傳遞的列表/元組?

+0

它在這裏:http://docs.python.org/dev/library/itertools.html#itertools-recipes。這已被問了很多次。 http://stackoverflow.com/questions/4578590/python-equivalent-of-filter-getting-two-output-lists-ie-partition-of-a-list – tokland

回答

0

被盜無恥地從this question - 您可以使用tee功能從itertools

from itertools import tee 

def split_on_condition(seq, condition): 
    l1,l2 = tee((condition(item),item) for item in seq) 
    return (i for p, i in l1 if p), (i for p, i in l2 if not p) 
+0

無需複製和粘貼,我們可以關閉該問題作爲一個確切的重複 – tokland